How to get the first element of the List or Set? [duplicate]
I'd like to know if I can get the first element of a list or set. Which method to use?
Solution 1:
See the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Solution 2:
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.)
Solution 3:
In Java >=8 you could also use the Streaming API:
Optional<String> first = set.stream().findFirst();
(Useful if the Set/List may be empty.)