Home > Blockchain >  Java 8 How to sum every elements in a list of a list using stream?
Java 8 How to sum every elements in a list of a list using stream?

Time:11-08

How can I sum every element in a list of list using Java 8 stream? For example, I have 3 different list in a list and I am trying to sum every element in each list and create another List. I am new to Java 8 and trying to solve some questions using stream api. Any help will be greatly appreciated!

List<List<Integer>> cases = [[1,1,2],[3,3,2],[4,5,1]];

The output that I am trying to achieve:

{[4,8,10]}

CodePudding user response:

You can do it like this:

List<List<Integer>> cases = Arrays.asList(Arrays.asList(1, 1, 2), Arrays.asList(3, 3, 2), Arrays.asList(4, 5, 1));

List<Integer> result = cases.stream()
        .map(list -> list.stream().mapToInt(Integer::intValue).sum())
        .collect(Collectors.toList());

System.out.println(result); // print [4, 8, 10]

CodePudding user response:

You can use the Stream API and reduce the internal lists to get the sum of their elements.

Demo:

import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<List<Integer>> cases = List.of(List.of(1, 1, 2), List.of(3, 3, 2), List.of(4, 5, 1));
        List<Integer> result = cases.stream()
                                    .map(e -> e.stream().reduce(0, Integer::sum))
                                    .collect(Collectors.toList());
        System.out.println(result);
    }
}

Output:

[4, 8, 10]

ONLINE DEMO

  • Related