Learnitweb

Find the First Element of a List

Approach 1: Using findFirst()

List<String> list = Arrays.asList("a","b","c");
String first = list.stream().findFirst().orElse(null);
System.out.println(first); // a

Why it works:

  • findFirst() returns an Optional.
  • orElse(null) provides a default in case the list is empty.

Approach 2: Using limit(1) and collectingAndThen (Alternative)

List<String> list = Arrays.asList("a","b","c");
String first = list.stream()
                   .limit(1)
                   .collect(Collectors.collectingAndThen(
                       Collectors.toList(),
                       l -> l.isEmpty() ? null : l.get(0)
                   ));
System.out.println(first); // a

Why it works:

  • limit(1) restricts the stream to one element.
  • collectingAndThen applies post-processing to extract the element.