How to get the first element of the List or Set?
To get the first element of a List
or Set
in Java, you can use the following methods:
List
:
List<String> list = new ArrayList<>();
// add elements to the list
String first = list.get(0);
Note that this will throw an IndexOutOfBoundsException
if the list is empty.
Set
:
Set<String> set = new HashSet<>();
// add elements to the set
String first = set.iterator().next();
Note that this will throw a NoSuchElementException
if the set is empty.
Alternatively, you can use the stream()
method to get the first element of a List
or Set
in a more concise way:
List<String> list = new ArrayList<>();
// add elements to the list
String first = list.stream().findFirst().orElse(null);
Set<String> set = new HashSet<>();
// add elements to the set
String first = set.stream().findFirst().orElse(null);
This will return an Optional<T>
object containing the first element of the List
or Set
, or an empty optional if the list or set is empty. You can then use the orElse()
method to specify a default value to be returned if the optional is empty.