PixelCoder
PixelCoder

Reputation: 61

How to sum every elements in a list of a list using stream?

How can I sum every element in a list of lists using Java 8 stream?

For example, I have 3 different lists 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:

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

The output that I am trying to achieve:

{[4,8,10]}

Upvotes: 1

Views: 2157

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

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

Upvotes: 5

b.GHILAS
b.GHILAS

Reputation: 2303

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]

Upvotes: 7

Related Questions