I currently use the following approach, but the syntax feels a bit off. Can this code be optimized?
Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();
I currently use the following approach, but the syntax feels a bit off. Can this code be optimized?
Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();
Been working with Java streams quite a bit lately, and your current approach is actually quite solid! You’re already leveraging mapToInt(i -> i)
to create an IntStream
, which is perfect for summing. That said, you can tighten it up just a bit by replacing the lambda with a method reference—it makes the code a bit cleaner and easier to read:
int sum = integers.values().stream().mapToInt(Integer::intValue).sum();
This way, your intent is crystal clear, and you’re still fully taking advantage of the java stream sum
capabilities.
Totally agree, Emma. I’ve used that approach in a lot of projects myself. That said, if you want to express the summing operation more explicitly, there’s a neat trick using reduce
. It skips the intermediate step of mapToInt
and goes straight to combining the values:
int sum = integers.values().stream().reduce(0, Integer::sum);
This might be a bit more intuitive for those who view stream operations as a sequence of transformations and reductions. It’s still leveraging java stream sum
under the hood, just with a slightly different lens
Nice, both solid takes. Having worked on performance-critical systems, I’ll add one more angle: sometimes simplicity wins. If all you’re doing is summing integers, and you’re not tied to using streams, a classic for-each loop gets the job done with minimal overhead:
int sum = 0;
for (int num : integers.values()) {
sum += num;
}
It’s not as sleek as java stream sum
methods, but for readability and raw performance—especially on smaller datasets—it’s hard to beat.