In Java Stream API, findFirst() method is used to find the first element of this stream. Method returns the first element as an Optional or an empty Optional if the stream is empty.
Syntax of the Stream.findFirst() method is as follows-
Optional<T> findFirst()
findFirst() is a short-circuiting terminal operation meaning it may terminate in finite time when presented with infinite input.
Java Stream findFirst() examples
1. An example to get first element from a Stream of Integers.
import java.util.Arrays; import java.util.List; import java.util.Optional; public class StreamFindFirst { public static void main(String[] args) { List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8); Optional<Integer> firstNumFromStream = list.stream().findFirst(); if(firstNumFromStream.isPresent()) { System.out.println("First Element in the Stream- " + firstNumFromStream.get()); }else { System.out.println("No element found"); } } }
Output
First Element in the Stream- 3
2. You can also use findFirst() method along with other Stream operations to get the first element from the resultant stream. For example using filter method to filter out elements which are less than 3 and then getting the first element from the resultant stream.
public class StreamFindFirst { public static void main(String[] args) { List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8); Optional<Integer> firstNumFromStream = list.stream() .filter(e -> e > 3) .findFirst(); if(firstNumFromStream.isPresent()) { System.out.println("First Element in the Stream- " + firstNumFromStream.get()); }else { System.out.println("No element found"); } } }
Output
First Element in the Stream- 9
3. Using with Stream of strings. In the example findFirst() is used to get the first name that starts with “M”.
public class StreamFindFirst { public static void main(String[] args) { List<String> nameList = Arrays.asList("Andy", "Mona", "Vikram", "Jenny", "Meena"); Optional<String> firstName = nameList.stream() .filter(e -> e.startsWith("M")) .findFirst(); if(firstName.isPresent()) { System.out.println("First Element in the Stream- " + firstName.get()); }else { System.out.println("No element found"); } } }
Output
First Element in the Stream- Mona
That's all for this topic Java Stream - findFirst() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment