Introduction
Java Streams provide many out-of-the-box powerful features. In this article, we will look into some of the lesser-used or known features among the developers.
🚀 Unlock Your Path to Success with the Ultimate Everything Bundle! 🚀
Introducing the Everything Bundle — your one-stop solution to mastering Java, Spring Boot, SQL, acing interviews, and securing certifications!
Stream.ofNullable
This method was introduced in Java 9 and helps filter all the null values from the collection, potentially saving us from null pointer exceptions.
In the example below we have a names list that contains null, which we filter using the Stream.ofNullable method.
[Alice, Bob, Charlie]
2. Stream.iterate()
iterate() method is used for creating infinite streams of sequences. It takes seed and unary function that applies the function to the previous element.
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
In the below example, our seed is 0, and the unary operator is n -> n+2.
0
2
4
6
8
10
12
14
16
18
Since iterate() generates infinite streams we should have some termination such as limit, findFirst, or findAny, etc. to avoid an infinite loop.
Keep reading with a 7-day free trial
Subscribe to Java Newsletter to keep reading this post and get 7 days of free access to the full post archives.