Solution
OTHER TIPS
It's a pretty easy one to implement yourself, to be honest:
public static <T> T single(Iterable<T> source) {
Iterator<T> iterator = source.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("No elements");
}
T first = iterator.next();
if (iterator.hasNext()) {
throw new IllegalArgumentException("More than one element");
}
return first;
}
(Or put it in a generic class instead of making the method generic. You may decide to use a different exception type, too.)
A less defensive version of @Jon's solution.
Collection<T> coll;
T first = col.iterator().next();
Add checks to taste.
If you can use my xpresso library you can write: x.list(iterable).toScalar();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow