When using Java 8 Stream API, is there a benefit to combining multiple map calls into one, or does it not really affect performance?
For example:
stream.map(SomeClass::operation1).map(SomeClass::operation2);
versus
stream.map(o -> o.operation1().operation2());
Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.
A recap on Collectors toMap It takes the key and the value mapper. Uses a throwing merger (throws an exception) as the default merge function when it encounters a duplicate key. It returns the result in an HashMap (it is an implementation detail – not to be relied upon). It takes the key and the value mapper.
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another.
The performance overhead here is negligible for most business-logic operations. You have two additional method calls in the pipeline (which may not be inlined by JIT-compiler in real application). Also you have longer call stack (by one frame), so if you have an exception inside stream operation, its creation would be a little bit slower. These things might be significant if your stream performs really low-level operations like simple math. However most of the real problems have much bigger computational cost, so relative performance drop is unlikely to be noticeable. And if you actually perform a simple math and need the performance, it's better to stick with plain old for
loops instead. Use the version you find more readable and do not perform the premature optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With