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.
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.
The easiest answer is what you've done!
first = collection.iterator().next();
note that iterator() is a method, was that a typo?
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