Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream string of map calls versus combining into one [duplicate]

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());
like image 493
Mike Avatar asked Jan 27 '16 21:01

Mike


People also ask

Is Java 8 stream faster than for loop?

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.

How do you handle duplicate keys in collectors toMap?

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.

What are the two types of streams proposed by Java 8?

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.

What is the purpose of the MAP method in Java 8 streams?

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.


1 Answers

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.

like image 159
Tagir Valeev Avatar answered Oct 13 '22 20:10

Tagir Valeev