Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first (and only value) from a collection [duplicate]

Tags:

Possible Duplicate:
Java: Get first item from a collection

In Java, I often encounter a collection with one single element, which I need to retrieve. Because collections do not guarantee consistent ordering, there is no first() or get(int index) methods, so I need to use rather ugly things, such as:

public Integer sillyExample(Collection<Integer> collection){     if(collection.size()==1){         return collection.iterator().next();     }     return someCodeToDecideBetweenElements(collection); } 

So, how do you get the only element out? I can't believe there isn't a better way...

Please note, I understand there's no concept of "first", I'm just trying to avoid building an iterator when I know there is only one element in it.

EDIT: Peter Wooster found a very similar question here. I'm leaving this open because I'm not trying to get the "first" element, which would imply a consistent ordering, but the "one and only" element after checking that it indeed is the only element.

like image 210
Miquel Avatar asked Jan 16 '13 09:01

Miquel


People also ask

How do you access elements of collections?

It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements. elements next(): This method returns the next elements in the iterator. void remove(): This method removes from the collection the last elements returned by the iterator.


1 Answers

The easiest answer is what you've done!

first = collection.iterator().next(); 

note that iterator() is a method, was that a typo?

like image 71
Peter Wooster Avatar answered Oct 03 '22 04:10

Peter Wooster