How to get the first element of the List or Set? [duplicate] How to get the first element of the List or Set? [duplicate] java java

How to get the first element of the List or Set? [duplicate]


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()


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.)