In this tutorial, we will see “How to use findFirst vs findAny methods in a Stream in Java 8” with most simplest examples so that even beginners can understand with ease. In Java 8, you can use the Stream interface and it’s findFirst and findAny methods to find the first or any element in a stream that satisfies a given condition.
Java 8 stream findfirst vs findany
findFirst()
Here is an example of using findFirst
to find the first element in a stream of integers that is greater than 7:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Find first element from the list using findFirst method of Stream in Java 8 * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; import java.util.Optional; public class FindFirst_Java8Stream_Example { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Optional<Integer> firstNumberGreaterThanSeven = numbers.stream() .filter(n -> n > 7) .findFirst(); System.out.println("List: "+numbers.toString()); firstNumberGreaterThanSeven.ifPresent(n -> System.out.println("First Number which is greater than 7 in the list is: "+n)); } } |
Output:
1 2 | List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] First Number which is greater from 7 in the list is: 8 |
findAny()
findAny
works in the same way, but it returns an element chosen arbitrarily from the elements that satisfy the condition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** * Find any element from the list using findAny method of Stream in Java 8 based on a defined condition * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; import java.util.Optional; public class FindAny_Java8Stream_Example { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Optional<Integer> anyNumberGreaterThanSeven = numbers.stream() .filter(n -> n > 7) .findAny(); System.out.println("List: "+numbers.toString()); anyNumberGreaterThanSeven.ifPresent(n -> System.out.println("Any one Number which is greater than 7 in the list is: "+n)); } } |
Output:
1 2 | List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] First Number which is greater from 7 in the list is: 8 |
Filter/Remove null values from a List using Stream in Java 8...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams
filter null values from stream
Useful References: