Collectors averagingLong () method in Java 8


The averagingLong() method of the Collectors class returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.

The syntax is as follows

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

Here, the parameters

  • T - Type of the input elements
  • mapper - Function extracting the property to be summed
  • Double - It wraps a value of the primitive type double in an object.
  • ToLongFunction - A function that produces a long-valued result.

To work with Collectors class in Java, import the following package

import java.util.stream.Collectors;

The following is an example to implement averagingLong() method in Java

Example

 Live Demo

import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("20", "50", "75", "100", "150", "200");
      double res = stream.collect(Collectors.averagingLong(a -> Long.parseLong(a)));
      System.out.println("Arithmetic Mean of the stream elements = "+res);
   }
}

Output

Arithmetic Mean of the stream elements = 99.16666666666667

Updated on: 30-Jul-2019

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements