How to Get the First Element in the Optional List using Java 8 – Detailed Guide

The Java 8 Stream API has introduced findFirst() method which returns an Optional holding the first element of the Stream.
This tutorial will teach you possible ways to get the first element from a List.

Using Stream findFirst() method

The findFirst() method returns any Optional element of a Stream when the order is not specified.
If Stream is empty, the findFirst() method will return an empty Optional value, and If the selected element is null, then NullPointerException will be thrown.

Note: The findFirst() method is considered a short-circuiting terminal operation.

Code

    List<String> numbers = Arrays.asList("5","3","6","1","4","2");
    Optional<String> firstElement = numbers.stream().findFirst();  
    System.out.println(firstElement);

    Optional<String> sortedFirstElement = numbers.stream().sorted().findFirst();  
    System.out.println(sortedFirstElement);

Output

    Optional[5]
    Optional[1]

In the above example, The first scenario does not have any order specification. So the list’s first element[Optional[5]] is printed. Still, in the second scenario, the list is sorted in ascending order(default sort); as a result, Optional[1] becomes the first element.
Code

    List<List<String>> emptyList = new ArrayList<>();  
    String firstElement = emptyList.stream().flatMap(list -> list.stream().filter(Objects::nonNull)).findFirst().orElseGet(()-> "default");  
    System.out.println(firstElement);

    List<String> numbers = Arrays.asList("5","3","6","1","4","2");  
    List<String> numbers2 = Arrays.asList("7","8","9","10");
    List<List<String>> nestedList = Arrays.asList(numbers, numbers2);  
    Optional<Integer> firstElement = nestedList.stream().flatMap(list -> list.stream().filter(Objects::nonNull)).map(x->Integer.valueOf(x)).filter(x->x>5).findFirst();  
    System.out.println(firstElement);

Output

    default   
    Optional[6]


In the first scenario, Java 8 .flatMap() combines multiple lists and uses stream.filter() to retain the NonNull objects. The .findFirst() method will return an empty Optional value as the empty list is used. Instead of returning an empty Optional value, .orElseGet() is used to return the default value(default).

Using lambda expression to filter and findFrist() Object in a list

The findFirst() method can also be used to get the first element in the list of Objects.
Code

    //Employee class
    public class Employee {  
        private String id;  
         private String name;  
    }

    employeeList = [
      {
        "id": "3",
        "name": "Maxwell"
      },
      {
        "id": "2",
        "name": "Axar"
      },
      {
        "id": "1",
        "name": "Ajmal"
      }
    ]
    Optional<Employee> firstEmployee = employeeList.stream().filter(x->x.getName().startsWith("A")).findFirst();  
    System.out.println(firstEmployee);

Output

    Optional[Employee(id=2, name=Axar)]

The list can be sorted using Comparator and get the sorted first element.
Code

    Comparator<Employee> employeeComparator = (a, b) -> a.getName().compareTo(b.getName());  
    Optional<Employee> sortedFirstEmployee = employeeList.stream().sorted(employeeComparator).filter(x->x.getName().startsWith("A")).findFirst();  
    System.out.println(sortedFirstEmployee);

Output

    Optional[Employee(id=1, name=Ajmal)]


In the above example, Comparator uses the Employee object’sname field for sorting.

Using Stream.limit()

The Stream.limit() method can also be used to get the first element in a Stream.
Code

    List<String> numbers = Arrays.asList("5","3","6","1","4","2");
    List<String> firstElementAsList = numbers.stream().limit(1).toList();  
    System.out.println(firstElementAsList);

Output

    [5]


The Stream object is limited to 1 using the .limit(1) method and returns the first element.

Related Topics

Leave a Comment