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.
T
> findFirst().Optional<T
> findFirst()
//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
//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
//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)