0 votes
1 view
in Java by (10.2k points)

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

1 Answer

0 votes
by (46.1k points)

This will help, but the i -> i is performing some automatic unboxing which is why it "feels" confusing . You can try both and better explain what the compiler is performing under the hood with your initial syntax:

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

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 10, 2019 in Java by Suresh (3.4k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...