Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the object of a singleton collection

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.)

like image 458
Alex Avatar asked Jul 30 '12 07:07

Alex


3 Answers

Iterables.getOnlyElement() (or Iterables.getFirst(), if collection can be empty) from Guava.

like image 170
axtavt Avatar answered Oct 21 '22 19:10

axtavt


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 :)

like image 22
Martijn Courteaux Avatar answered Sep 20 '22 22:09

Martijn Courteaux


With Java 8 you can do:

collection.stream().findAny().get();
like image 1
gvlasov Avatar answered Oct 21 '22 19:10

gvlasov