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();
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 anIntStream
"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: