How to get the first element of the List or Set? [duplicate]
Collection c;Iterator iter = c.iterator();Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set
. You should realize that it has absolutely no meaning for most implementations of Set
. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
In Java >=8 you could also use the Streaming API:
Optional<String> first = set.stream().findFirst();
(Useful if the Set/List may be empty.)