Stream findFirst() Method

The findFirst() method is a part of Short circuit operation in Java Stream. It returns an Optional 1st element of the stream or empty if the stream is empty.

  1. The findFirst() method is a part of stream short circuit operation.
  2. It returns an Optional 1st element of the stream or empty if the stream is empty.
  3. Syntex is Optional<T> findFirst().

Syntax:

Optional<T> findFirst()

Example of findFirst() method of Strings in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

  public static void main(String args[]) {
    List<String> strList = new ArrayList<String>();
    strList.add("One");
    strList.add("Two");
    strList.add("Three");
    strList.add("Four");
    strList.add("Five");

    Optional<String> firstElement = strList.stream().findFirst();

    System.out.println(firstElement);
    System.out.println(firstElement.get());
 
  }
}

Output:
Optional[One]
One

Example of findFirst() method of Integers in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

  public static void main(String args[]) {
    List<Integer> intList = new ArrayList<Integer>();
    intList.add(100);
    intList.add(90);
    intList.add(80);
    intList.add(70);
    intList.add(200);

    Optional<Integer> firstElement = intList.stream().findFirst();

    System.out.println(firstElement);
    System.out.println(firstElement.get());

    }
}

Output:
Optional[100]
100

Example of findFirst() method of empty list in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

  public static void main(String args[]) {
    List<String> strList = new ArrayList<String>();
    
    Optional<String> firstElement = strList.stream().findFirst();

    System.out.println( firstElement );
    System.out.println( "Optional.get() of empty" );
    System.out.println( firstElement.get() );
   
    }
}

Output:
Optional.empty
Optional.get() of empty
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:143)
	at com.school.stream.FindFirstExample.main(FindFirstExample.java:21)