I have a List with items, where each item is an object with a getter method I'm interested in. I want to run over the complete list to sum all those getter results.
When I do it with java 8 streams, it looks like this:
double currentProduction = itemList.stream().collect(
Collectors.summingDouble((e) -> e.getProduction(param)));
In plain old java, it looks like this:
for (Item item : itemList) {
currentProduction += item.getProduction(param);
}
Both methods yield exactly the same result, but my logger reports that for each item instance the getProduction() method is run TWICE in case of the java 8 stream solution. In the plain old java list iteration solution the getProduction method is just run once per instance, as expected.
As the getProduction method is quite costly, this is an issue for me.
Why is this? And what can I do about this (besides using just the for loop)?