Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
collectors

What is Collectors.averagingInt() in Java?

abhilash

Overview

Collectors is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, etc.

The different functionalities in the Collectors class are usually used as the final operation on streams.

The averagingInt() method

averagingInt() is a static method of the Collectors class. It is used to return a Collector that calculates the arithmetic meanOr the average of the result returned by applying the passed integer-valued ToIntFunction implementation to the input elements. If there are no elements, then the method returns zero.

The averagingInt method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, use the following import statement:

import java.util.stream.Collectors;
Import statement

Syntax

public static <T> Collector<T, ?, Double> averagingInt(ToIntFunction<? super T> mapper)
Syntax of the averagingInt() method

Parameters

  • ToIntFunction<? super T> mapper: The function to extract the property or attribute to be averaged.

Return value

This method returns the average of the elements returned due to the passed ToIntFunction implementation to all the input elements.

Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args)
    {
        List<Integer> integerList = Arrays.asList(23, 23, 8);

        System.out.println("Contents of the list - " + integerList);

        Stream<Integer> integerStream = integerList.stream();

        double averageOfElements = integerStream.collect(Collectors.averagingInt(e -> e));

        System.out.println("Average of the stream - " + averageOfElements);
    }
}
Implementation of the "averagingInt" method

Explanation

  • Lines 1 to 4: We import the relevant packages.
  • Line 10: We define a list of int values called integerList.
  • Line 12: We print the integerList.
  • Line 14: We create a stream out of the integerList.
  • Line 16: We find the average of the elements of the integerList using the averagingInt method. Here, the passed ToIntFunction implementation returns the passed element itself.
  • Line 18: We print the average of the elements of the stream.

RELATED TAGS

java
communitycreator
collectors
RELATED COURSES

View all Courses

Keep Exploring