Which java is equivalent to the C # Single () operator?

You know something equivalent:

<T> T single(List<T> list) { assertEquals(1, list.size()); return list.get(0); } 

Is there something like this in lambdaj?

+4
source share
4 answers

lambdaj has a selectUnique method that throws an exception if there is more than one element satisfying the condition expressed by the given match. Since you do not have any specific condition for matching, you need a Matcher that always returns true (it does not seem to me that hamcrest provides such a Matcher out of the box, but it is trivial to implement it), or maybe you want to check that the object (only ) in the list is at least non-zero, so you can achieve this result with:

 selectUnique(list, Matchers.notNullValue()); 
+1
source

Not exactly the same, 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. Please note that these collections are immutable (at the entrance to the structure).

0
source

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

0
source

If you can use my xpresso library, you can write:

 x.list(iterable).toScalar(); 
-1
source

Source: https://habr.com/ru/post/1334247/


All Articles