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>.
Using Stream.collect() asList(1, 2, 3, 4, 5); Integer sum = integers. stream() . collect(Collectors. summingInt(Integer::intValue));
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With