Close

Java 8 Streams - Collectors.averagingLong Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.Collectors

java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

Method:

public static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements. If no elements are present, the result is 0.


Examples


The method Collectors#averagingLong converts each stream elements to long per user provided mapper function and returns the arithmetic mean of those long values.

package com.logicbig.example.collectors;

import java.math.BigDecimal;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AveragingLongExample {
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.averagingLong(BigDecimal::longValue));
System.out.println("average: " + d);
}
}

Output

1
2
3
4
5
6
7
8
9
10
average: 5.5
Original Post




See Also