Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
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 (46k 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
asked Aug 10, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...