Java stream findFirst() explanation with example:
findFirst() is used to find the first element in a stream in Java. It returns one Optional value holding the element found. If the stream is empty, it will return one empty optional. In this post, I will show you how findFirst() works with an example.
Definition of findFirst:
findFirst is defined as below:
Optional<T> findFirst()
- It returns an optional value holding the element from the stream.
- It returns one empty optional if the stream is empty.
- It returns NullPointerException if the selected element is null.
Example of findFirst:
Let’s consider the below example program:
package com.company;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args){
Stream<Integer> intStream = Arrays.asList(10, 20, 30, 40, 50, 40).stream();
Optional firstValue = intStream.findFirst();
System.out.println(firstValue);
}
}
It will print Optional(10).
We can also check if a value exists or not using isPresent() and get the value using get():
package com.company;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args){
Stream<Integer> intStream = Arrays.asList(10, 20, 30, 40, 50, 40).stream();
Optional firstValue = intStream.findFirst();
if(firstValue.isPresent()){
System.out.println(firstValue.get());
}
}
}
It will print 10.
Example of using filter with findFirst:
We can also use filter with findFirst. filter can filter out a value in the stream and if we use findFirst with filter, we can get the first value that matches the filter condition.
For example:
package com.company;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args){
Stream<Integer> intStream = Arrays.asList(1, 4, 6, 7, 3, 9, 10).stream();
Optional firstValue = intStream.filter(x -> x%2 == 0).findFirst();
if(firstValue.isPresent()){
System.out.println(firstValue.get());
}
}
}
Here, we are using filter and findFirst to find the first even number in the number list. It will print 4 as the output.
You might also like:
- Java 8 Stream min and max method examples
- Java 8 example to convert a string to integer stream (IntStream)
- Java program to read contents of a file using FileInputStream
- Java program to find the total count of words in a string
- Java program to print random uppercase letter in a string
- Java program to read and print a two dimensional array