开发者

What's java equivalent to C#'s Single() operator?

You know, something equivalent to:

<T> T single(List<T> list) {
  assertEquals(1, list.size());
  return list.get(0);
}
开发者_如何学C

Does lambdaj contain something like that?


lambdaj has the selectUnique method that throws an exception if there is more than one item satisfying the condition expressed by the given hamcrest Matcher. Since you don't have any particular condition to be matched, you need a Matcher that always returns true (it doesn't seem to me that hamcrest provides such a Matcher out of the box, but it is trivial to implement it), or maybe you would like to check that the (only) object in the list is at least not null, so you could achieve this result with:

selectUnique(list, Matchers.notNullValue());


Not quite the same thing, but Java has a way to create lists (and other collections) that are guaranteed to have only one element. Take a look at Collections.singleton* methods. Note that these collections are immutable (with entry provided at constructions).


If you can use my xpresso library you can write:

x.list(iterable).toScalar();


Guava has an Iterables.getFirst() method that does exactly that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜