I want to get the object of a collection that I know has exactly one element (basically it's the reverse of what Collections.singletonList()
does - but I don't know whether the collection is list/set/something else so I can't use c.get(0)
).
Currently I use c.iterator.next()
, wonder if there is already a method for that in Java or one of the common libraries (apache-commons, guava etc.)
Iterables.getOnlyElement()
(or Iterables.getFirst()
, if collection can be empty) from Guava.
The method signature and the JavaDoc clearly say it is a List
.
This is the signature:
public static <T> List<T> singletonList(T o)
And this is the JavaDoc:
Returns an immutable list containing only the specified object. The returned list is serializable.
So, this means that you can simply use:
List<MyClass> singleton = Collections.singletonList(myObject);
MyClass obj = singleton.get(0);
Ow, now I see what you mean. I have to admit that your question was clear. But for one or another reason, I didn't understand :)
With Java 8 you can do:
collection.stream().findAny().get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With