- Java Stream findFirst()
- Java stream get first element
- 2. Java stream API
- 3. Java stream get first element
- 4. Get first element example
- 5. Conclusion
- Java stream get first n elements
- 2. Java stream API
- 3. Java stream get first n elements
- 4. Java stream get the first element
- 4. Get first element example
- 5. Conclusion
- 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
Java Stream findFirst()
The findFirst() method returns an Optional describing the first element of the given stream if Stream is non-empty, or an empty Optional if the stream is empty.
1. Stream findFirst() Method
- The findAny() method is a terminal short-circuiting operation.
- The findFirst() method returns an Optional .
- The Optional contains the value as first element of the given stream, if Stream is non-empty.
- The Optional contains the empty value, if Stream is empty.
- If the element selected is null , NullPointerException is thrown.
- If Stream has defined encounter order, the findFirst() returns first element in encounter order.
- If Stream has no encounter order, the findFirst() may return any element.
- The above behavior is vaid for all sequential and parallel streams. The behavior of findFirst() does not change by the parallelism of the Stream.
2. Stream findFirst() Example
In the given example, we are getting the first element from the Stream . As soo as, we get the first element, the stream operation moves to ifPresent() method.
We print the first element in using the method reference inside ifPresent() method.
import java.util.stream.Stream; public class Main < public static void main(String[] args) < //sequential stream Stream.of("one", "two", "three", "four") .findFirst() .ifPresent(System.out::println); //parallel stream Stream.of("one", "two", "three", "four") .parallel() .findFirst() .ifPresent(System.out::println); >>
3. Stream findFirst() vs findAny()
In non-parallel streams, findFirst() and findAny() , both may return the first element of the Stream in most cases. But findAny() does not offer any guarantee of this behavior.
Use findAny() to get any element from any parallel stream in faster time. Else we can always use findFirst() in most of the cases.
Java stream get first element
In this article, we will learn to get the first element from a Java stream. To learn more about other Java stream utility functions, refer to these articles.
2. Java stream API
The Stream API introduced in Java 8 is used to process a collection of objects. It represents a sequence of objects and provides various utility methods to produce the desired result.
3. Java stream get first element
The Java stream provides the findFirst utility function to get the first element of the stream. The syntax of the findFirst is:
It returns Optional as output, where T refers to the type of the result being returned. If the stream is empty, then returns empty Optional .
Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Usually, we use Optional to show the absence of the result and where using null is likely to cause errors.
You can check whether the value is present before invoking get function for the result.
4. Get first element example
For example, the following code uses the findFirst function to return the first element of the stream. As you can see, we checked whether the element is present in the Optional container before retrieving the result using the get() function.
public static void main(String args[]) < Listvowels = Arrays.asList("A", "E", "I", "O", "U"); Optional firstElement = vowels.stream().findFirst(); if (firstElement.isPresent()) < System.out.println(firstElement.get()); >>
If you execute the above code, it prints the following result:
5. Conclusion
To sum up, we have learned to find the first element of the stream. You can find code samples in our GitHub repository.
Java stream get first n elements
In this article, we will learn to get the first n elements of the Java stream. To learn more about other Java stream utility functions, refer to these articles.
2. Java stream API
The Stream API introduced in Java 8 is used to process a collection of objects. It represents a sequence of objects and provides various utility methods to produce the desired result.
3. Java stream get first n elements
The Java stream provides the limit function to return the result stream comprising the first n elements of the provided stream.
For example, the following limit function takes the stream of elements and sets the limit size as 3. It truncates the first 3 elements and returns them as the stream of elements. We converted it to a list using the Collectors.toList() .
public static void main(String args[]) < Listvowels = Arrays.asList("A", "E", "I", "O", "U"); Stream result = vowels.stream().limit(3); List resultList = result.collect(Collectors.toList()); System.out.println(resultList); >
If you execute the above code, it returns the following result:
4. Java stream get the first element
The Java stream provides the findFirst utility function to get the first element of the stream. The syntax of the findFirst is:
It returns Optional as output, where T refers to the type of the result being returned. If the stream is empty, then returns empty Optional .
Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Usually, we use Optional to show the absence of the result and where using null is likely to cause errors.
You can check whether the value is present before invoking get function for the result.
4. Get first element example
For example, the following code uses the findFirst function to return the first element of the stream. As you can see, we checked whether the element is present in the Optional container before retrieving the result using the get() function.
public static void main(String args[]) < Listvowels = Arrays.asList("A", "E", "I", "O", "U"); Optional firstElement = vowels.stream().findFirst(); if (firstElement.isPresent()) < System.out.println(firstElement.get()); >>
If you execute the above code, it prints the following result:
5. Conclusion
To sum up, we have learned to find the first n elements of the stream. You can find code samples in our GitHub repository.
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.