javajava-8java-stream

How to sum a list of integers with java streams?


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

Solution

  • You can use collect method to add list of integers.

    List<Integer> list = Arrays.asList(2, 4, 5, 6);
    int sum = list.stream().collect(Collectors.summingInt(Integer::intValue));