Java Stream — Cheat Sheet
I hope you already know how to use Java Stream, as it was introduced on Java 8. However, do you know how it works, and what are the main methods you can use?
Let’s see what are the methods and how they work.
Stateless vs. Stateful:
Stateless operations process each element independently (e.g.,
filter()
,map()
).Stateful operations depend on previous elements (e.g.,
sorted()
,distinct()
).
Be careful, using Stateful operations with Parallel Stream can give you a wrong result.
Intermediate vs. Terminal:
Intermediate operations return a stream and allow chaining (e.g.,
filter()
,map()
).Terminal operations produce a result or a side effect (e.g.,
collect()
,reduce()
,forEach()
).
Bonus: Interview question:
Q: Are Java Streams considered lazy, and how does it work?
R: Java Streams are lazy because intermediate operations (like filter()
, map()
) are not executed until a terminal operation (like collect()
, forEach()
) is invoked. This allows streams to optimize performance by processing data only when necessary and avoiding unnecessary operations.
Conclusion
Java Stream is a popular feature of Java that allows the developers to do many operations through collections in a lazy mode, using the functional programming idea.
Knowing the main methods and how Java Stream works is crucial for increasing your productivity and reducing the chances of bugs.
I hope this article has helped you. Did you know all these methods?