How to sum a list of integers with java streams?

membersound picture membersound · May 8, 2015 · Viewed 394.1k times · Source

I want to sum a list of integers. It works as follows, but the syntax does not feel right. Could the code be optimized?

Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();

Answer

Necreaux picture Necreaux · May 8, 2015

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:

integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();