How to sum the values in List<int[]> using Java 8
You want to flatMap
to an IntStream
. After that, taking the sum is easy.
int sum = counts.stream()
.flatMapToInt(IntStream::of)
.sum();
int sum = counts.stream().flatMapToInt(array -> IntStream.of(array)).sum();
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