What is the difference between
stream.map().limit(5).terminalOperation()
and this line
stream.limit(5).map().terminalOperation()
the both lines will return the same result, but which one is more optimized and will not consume more time and resources ? and why ? and how many times the map will be called in each case?
how many times the map will be called in each case?
The answer depends on the terminal operation, not on the order of map
and limit
.
The terminal operation may consume just one element (findFirst()
) or all elements (collect()
).
Either way, the terminal operation dictates the number of elements on which map
is performed, which should be identical in both cases.
For example, if you collect the elements to a List
, assuming the Stream
source has at least 5 elements, map
will be executed 5 times for each pipeline.
You can verify that by adding a println
statement to the map
step:
List<String> list = Arrays.asList ("a","b","c","d","e","f");
list.stream().map(l->{System.out.println ("map1 " + l);return l +"44";}).limit(5).collect(Collectors.toList());
list.stream().limit(5).map(l->{System.out.println ("map2 " + l);return l +"44";}).collect(Collectors.toList());
This will output:
map1 a
map1 b
map1 c
map1 d
map1 e
map2 a
map2 b
map2 c
map2 d
map2 e
Either way, map
is not executed for the 6th element.
As to which variant to prefer, I'm assuming they'll have similar running time, but that depends on the actual implementation.