Java – How to Sum a List of Integers with Java Streams

javajava-8java-stream

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();

Best Answer

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. mapToInt converts the stream to an IntStream "of primitive int-valued elements". 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();
Related Question