- How to find the first element in Stream in Java 8? findFirst() Example
- Java 8 findFirst() Example
- Java Program to find the first element of Stream in JDK 8
- Java 8 Stream filter() + findFirst Example Tutorial
- How to find the first element from a Stream with a filter
- Java 8 Stream filter + findFirst Example
How to find the first element in Stream in Java 8? findFirst() Example
In Java 8, you can use the Stream.findFirst() method to get the first element of Stream in Java. This is a terminal operation and is often used after applying several intermediate operations e.g. filter, mapping, flattening, etc. For example, if you have a List of String and you want to find the first String whose length is greater than 10, you can use the findFirst() method along with stream() and filter() to get that String. The stream() method gets the Stream from a List, which then allows you to apply several useful methods defined in the java.util.Stream class like filter() , map() , flatMap() etc.
One of the important things to know while using for writing such logic is that all intermediate operations e.g. filter() , map(), etc are lazy and they are only executed when a terminal operation like findFirst() or forEach() is called.
This also means, a lot of opportunities for optimization depending upon the size of the original list. In this article, I’ll show you a couple of examples of the findFirst() method with Predicate to show the true power of Stream in Java 8.
You can also join these Functional Programming and Stream APIcourses for some really good examples and explanations. The instructor of these online courses has done a fabulous job of explaining tricky Java 8 concepts in simple words.
Java 8 findFirst() Example
Let’s say, we have a List of String and we want to find out the first String which has a length greater than 10, how do you solve this problem before Java 8? Well, in Java 6 or 7 you can use the enhanced for loop as shown below to get the first String which satisfies our requirement as shown below:
for (String gadget : gadgets) < if (gadget.length() > 10) < System.out.println("Prior ot Java 8: " + gadget); break; > >
In Java 8, you can achieve the same effect by using the findFirst() method of java.util.stream.Stream class as shown below:
String item = gadgets.stream() .filter(s -> s.length() > 10) .findFirst() .orElse("");
Many Java Programmers think that this is an inefficient approach because it looks like the filter() method is scanning the whole list as opposed to breaking on the first element as we have done in our prior to Java 8 example.
This is not true, Java 8 example is as efficient as the one before. The filter() is an intermediate operation that is lazy and only evaluated when you call a terminal method like the forEach() method or findFirst() method as in this case.
This means the filter() will not scan the whole list but only the first few elements until it got the one whose length is greater than 10. You can verify this by using the peek() method which prints the output of what happening during stream processing steps as shown below:
String item = gadgets.stream() .peek(s -> System.out.println("processing: " + s)) .filter(s -> s.length() >8) .findFirst() .orElse(""); Output: processing: SmartPhone result: SmartPhone
You can see that filter() has processed just one element from the Stream. Once it found the «SmartPhone» , it stops because that satisfies the findFirst() method.
Also, it’s worth knowing that all intermediate stream operations are lazy (See Java 8 in Action). They are the operation that returns another Stream instead of value. The terminal operation returns a value or creates a side-effect. So, don’t worry about performance, one of the key reason for using stream is lambda is a lazy evaluation which presents optimization opportunity depending upon the algorithm.
Java Program to find the first element of Stream in JDK 8
Here is our Java program to demonstrate how you can use stream utility methods like map(), flatMap(), and findFirst() to filter and find out the first element from Stream in Java 8.
import java.util.ArrayList; import java.util.List; /* * Java Program to show how to find the first element * of Stream in Java 8. */ public class Java8Demo < public static void main(String args[]) < // a list of electronic gadgets ListString> gadgets = new ArrayList<>(); gadgets.add("SmartPhone"); gadgets.add("SmartWatch"); gadgets.add("SmartTV"); gadgets.add("SmartDoor"); gadgets.add("iPhone"); // printing gadgets whose length is greater than 7 // using pre Java 8 techniques for (String gadget : gadgets) < if (gadget.length() > 7) < System.out.println("Prior ot Java 8: " + gadget); break; > > // retrieving gadgets with length greater than 8 // using lambda expression and stream methods // in Java 8 String item = gadgets.stream() .filter(s -> s.length() > 8) .findFirst() .orElse(""); System.out.println("In Java 8, first item: " + item); // you can further use peek() to see // what's going inside filter or other stream // methods. String myItem = gadgets.stream() .peek(s -> System.out.println("processing: " + s)) .filter(s -> s.length() > 8) .findFirst() .orElse(""); System.out.println("result: " + myItem); > > Output: Prior ot Java 8: SmartPhone In Java 8, first item: SmartPhone processing: SmartPhone result: SmartPhone
That’s all about how to find the first element in Stream in Java 8. You can use the findFist() method to get the first object. It’s a terminal operation and should be the last call on stream because after that you cannot call any method on Stream. Intermediate operations are evaluated lazily.
- 20 Examples of Date and Time in Java 8 (tutorial)
- How to use Stream class in Java 8 (tutorial)
- How to use filter() method in Java 8 (tutorial)
- How to use forEach() method in Java 8 (example)
- How to join String in Java 8 (example)
- How to convert List to Map in Java 8 (solution)
- How to use peek() method in Java 8 (example)
- 5 Books to Learn Java 8 from Scratch (books)
- How to convert the stream to array in Java 8 (tutorial)
- Java 8 Certification FAQ (guide)
- Java 8 Mock Exams and Practice Test (test)
Java 8 Stream filter() + findFirst Example Tutorial
Suppose, you have a list of prime numbers and you need to find the first prime number which is greater than a given number? How do you find it? Don’t tell that you will loop through the list and check each element and return the first element which is greater than the given number. Well, that’s right but that’s not what you should do in Java 8. That’s good for Java 7 or earlier version but Java 8 offers you many better alternatives and one of them is Stream. You can use the Stream class along with filter() and findFirst() methods to find out an element based upon a Predicate , a functional interface for defining a condition which returns a boolean.
The java.util.stream.Stream class provides a couple of find methods to search elements in Stream, findFirst() and findAny() .
As the name suggests, the findFirst method returns the first element from the Stream, wrapped in an Optional, but only if the Stream maintains an order like a Stream generated from an ArrayList or LinkedHashMap which keeps elements in order.
If Stream doesn’t maintain order then any element will be returning and this is what the findAny() method does. It returns an element from Stream.
That’s why it’s not guaranteed to receive the same element if you call this method again.
Both findFirst() and findAny() are short-circuit methods, much like short circuit AND (&&) and OR (||) operators which will not evaluate any more elements once they found one. If you are not familiar with what is a short circuit operation in Java, I suggest you go through the Complete Java Masterclass course on Udemy, one of the most comprehensive courses on Java.
How to find the first element from a Stream with a filter
Now, let’s come back to the task at hand. As the problem statement says, we have a list of prime numbers in the increasing order e.g. 2, 3, 5, 7, 11, 13 and we need to find the first prime number which is greater than 5 i.e. our code should return 7.
In order to achieve that we’ll first get the Stream from the List and then call the filter() method with the predicate number > 7 , after that we’ll call the findFirst() method. This will give us the result.
If you remember, filter() is an intermediate method which means after applying a filter, you can still call other methods on stream. It’s also lazy which means it will not do anything until you call a terminal method like findFirst() . You can further see Learn Java Functional Programming with Lambdas and Stream course by Ranga Karnam to learn more about Stream features.
Java 8 Stream filter + findFirst Example
Here is the code to find the first element from a List in Java 8 after applying a predicate:
import java.util.Arrays; import java.util.List; /** * * A simple example find the first element from * List based upon condition. * */ public class Hello < public static void main(String args[]) < List primes = Arrays.asList(2, 3, 5, 7, 11, 13); int primeGreaterThanFive = primes.stream() .peek(num -> System.out.println("will filter " + num)) .filter(x -> x > 5) .findFirst() .get(); System.out.println(primeGreaterThanFive); > > Output: will filter 2 will filter 3 will filter 5 will filter 7 7
The code is simple, except for the peek() and get() method. I have used peek() to demonstrate that filter will not do anything until you call the findFirst() method which is a terminal operation.
Since filter() is lazy it will only process the element needed to satisfy the criterion by findFirst() and that’s why all elements will not be required to process.
You can see that only 2, 3, 5, and 7 are processed to return the result. It has not touched 11 and 13.
If you change the condition to return prime which is greater than 3, then only 2, 3, and 5 will be touched. This provides a big performance boost if you are dealing with a large list e.g. something with 1 million numbers or Strings.
The get() method is used to retrieve a value from the Optional return by the findFrst() method. If you want you can also use the OrElse() method to define a default value just in case Optional is empty.
Btw, this is an extremely common code if you have started coding in Java because most of my Java 8 refactoring is replacing the loop with a functional equivalent. If you are also refactoring your code to take advantage of Java 8, I suggest you check out Heinz Kabutz’s Refactoring to Java 8 Streams and Lambdas course which provides many tips with the explanation to take full advantage of Java 8 features.
That’s all about how to find the first element from a List or Stream in Java 8 which satisfies a condition. As you can see that we can specify the condition using a Predicate, which is nothing but a Functional interface with just one method test() , which returns a boolean. You can use it along with methods like the filter to perform several interesting jobs in Java 8.
Btw, if you are just starting with Java 8 then The Complete Java SE 8 Developer BootCamp course on Udemy is a nice place to start with. It nicely covers all the Java 8 topics and also helps you to prepare for OCAJP 8.
- 5 Free Java 8 and Java 9 Courses for Developers
- How to do Map Reduce in Java 8?
- How to use flatMap in Java 8?
- 10 examples of the forEach() method in Java 8?
- 3 ways to read a file line by line in Java 8
- 10 examples of converting a List to Map of in Java 8?
- Top 5 Books to Learn Java 8 Better
- 10 Courses to learn Java for Beginners
- My favorite courses to learn Software Architecture
- Java 8 filter + map + collect example
- 10 Free Courses to learn Spring Framework for Beginners
- How to pass the Java SE 11 Certification Exam
P. S. — If you are keen to learn Java 8 Functional programming but looking for a free online training course to start with then you can also check out this Java 8 Functional Programming: Lambda Expressions Quickly course on Udemy. It’s completely free and you just need a Udemy account to join this course.