The method Collectors#averagingDouble converts the stream elements to primitive double per user provided mapper function and returns the arithmetic mean of those doubles.
package com.logicbig.example.collectors;
import java.math.BigDecimal;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AveragingDoubleExample {
public static void main (String[] args) {
Stream<BigDecimal> s = Stream.iterate(
BigDecimal.ONE, bigDecimal ->
bigDecimal.add(BigDecimal.ONE))
.limit(10).peek(System.out::println);
Double d = s.collect(Collectors.averagingDouble(BigDecimal::doubleValue));
System.out.println("average: " + d);
}
}
Output
1
2
3
4
5
6
7
8
9
10
average: 5.5
Original Post