Java Streams - Collectors averagingInt(ToIntFunction mapper) example








Collectors averagingInt(ToIntFunction<? super T> mapper) returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.

Syntax

averagingInt has the following syntax.

public static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)

Example

The following example shows how to use averagingInt.

import java.util.stream.Collectors;
import java.util.stream.Stream;
/*from w w  w  .j av  a  2s .c  om*/
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("1","2","3");
    
    double o =  s.collect(Collectors.averagingInt(n->Integer.parseInt(n)));

    System.out.println(o);
  }
}

The code above generates the following result.