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.