Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>.

like image 228
BreenDeen Avatar asked Dec 28 '17 19:12

BreenDeen


People also ask

How will you get the sum of all numbers present in a list using Java 8?

Using Stream.collect() asList(1, 2, 3, 4, 5); Integer sum = integers. stream() . collect(Collectors. summingInt(Integer::intValue));

How do you sum a list in Java?

A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.


2 Answers

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

int sum = counts.stream()         .flatMapToInt(IntStream::of)         .sum(); 
like image 95
Ward Avatar answered Nov 01 '22 11:11

Ward


int sum = counts.stream().flatMapToInt(array -> IntStream.of(array)).sum(); 
like image 27
JB Nizet Avatar answered Nov 01 '22 11:11

JB Nizet