In this short post I am going to present Java 8 streams best practices. Most of them either I figured out myself or learned from my colleagues.
Let’s start with some “obvious” things about code formatting:
- You should have at most one stream method call per line.
This will make stream operations like
- You should
import staticall of the standard stream related methods. This will make code shorter, easier to read and easier to understand by removing all unnecessary visual noise.
- You should prefer method references to lambdas.
Method references are easier to read since we
avoid all the visual noise generated by
They are also handled more efficiently by current version of Java.
Lambda expressions like
s -> s.length() are compiled
to a private static method and an
Method references are compiled to only
- You should use methods from
Class<T>to filter stream elements by a type and to cast stream elements to a type.
Also rember that
Class<T>::isInstance only checks if
the value can be assigned to a variable of type
T. For example
true because string
"foo" can be assigned to a variable of type
If you want to check that stream elements have exactly type
you must use expression:
- Give meaningful names to frequently used collector expressions. In most cases this means extracting collector expression into its own method.
You may also consider using static import for your own frequently used collectors.
- Use the following pattern when you sort stream values at hoc:
Notice how we used
reverseOrder() to reverse order of sorting
by name and id. Also bear in mind that it is always a good idea
to extract complicated comparers to its own method or a final field.
DoubleStreamwhen working with primitive types. They are faster (they avoid boxing) and easier to use (they add useful methods like
mapToObj to convert
between a stream and a specialized primitive stream.
Also learn about static helper methods exposed by specialized stream classes:
- Avoid using
peek(). Try to make your streams free of side-effects.
This list is by no means complete. I will try to add some more practices in the future. Bye!