BreenDeen
BreenDeen

Reputation: 722

How to sum the values in List<int[]> using Java 8

I want to find the sum of the List<int[]> using Java 8. Here is my attempt.

int sum = counts.stream().flatMap(i -> Stream.of(i).mapToInt(m)).sum();

However, I get the error cannot convert to Stream<Object> to <unknown>.

Upvotes: 22

Views: 6814

Answers (5)

Ward
Ward

Reputation: 2828

You want to flatMap to an IntStream. After that, taking the sum is easy.

int sum = counts.stream()
        .flatMapToInt(IntStream::of)
        .sum();

Upvotes: 33

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5794

You can do it this way:

int sum = counts.stream()                               // getting Stream<int[]>
                .mapToInt(a -> Arrays.stream(a).sum())  // getting an IntStream with the sum of every int[]
                .sum();                                 // getting the total sum of all values.

Upvotes: 5

Eran
Eran

Reputation: 393841

Your i is a primitive array (int[]), so Stream.of(i) will return a Stream<int[]>.

I suggest you first calculate the sum of each individual array and then sum all of them:

int sum=counts.stream()
              .mapToInt(ar->IntStream.of(ar).sum()) // convert each int[] to the sum 
                                                    // of that array and transform the
                                                    // Stream to an IntStream
              .sum(); // calculate the total sum

Upvotes: 7

Cardinal System
Cardinal System

Reputation: 3422

This worked for me:

int sum = counts.stream().mapToInt(i -> Arrays.stream(i).sum()).sum();

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691765

int sum = counts.stream().flatMapToInt(array -> IntStream.of(array)).sum();

Upvotes: 16

Related Questions