Java Collectors averagingInt() Method

The averagingInt() method in Java, part of the java.util.stream.Collectors class, is used to calculate the average of integer values obtained from processing a stream of objects. This method is useful when you need to determine the average of certain properties of the elements in a stream.

Table of Contents

  1. Introduction
  2. averagingInt() Method Syntax
  3. Understanding averagingInt()
  4. Examples
    • Basic Usage
    • Using averagingInt() with Filter
  5. Real-World Use Case
  6. Conclusion

Introduction

The averagingInt() method returns a Collector that calculates the average of integer values. This method is particularly useful when working with streams to compute the average of specific numeric properties of the elements.

averagingInt() Method Syntax

The syntax for the averagingInt() method is as follows:

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

Parameters:

  • mapper: A function that extracts the integer property from the elements in the stream.

Returns:

  • A Collector that calculates the average of the extracted integer values.

Throws:

  • This method does not throw any exceptions.

Understanding averagingInt()

The averagingInt() method allows you to calculate the average of integer values derived from the elements of a stream. This is useful in scenarios where you need to compute the average of specific properties, such as ages, scores, or any other integer attributes.

Examples

Basic Usage

To demonstrate the basic usage of averagingInt(), we will create a list of integers and calculate their average.

Example

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

public class AveragingIntExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

        // Calculate the average of the numbers
        double average = numbers.stream()
                                .collect(Collectors.averagingInt(Integer::intValue));

        System.out.println("Average: " + average);
    }
}

Output:

Average: 30.0

Using averagingInt() with Filter

This example shows how to use averagingInt() in conjunction with a filter to calculate the average of elements that meet a specific condition.

Example

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

public class AveragingIntWithFilterExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape");

        // Calculate the average length of words that start with the letter 'a'
        double averageLength = words.stream()
                                    .filter(word -> word.startsWith("a"))
                                    .collect(Collectors.averagingInt(String::length));

        System.out.println("Average length of words starting with 'a': " + averageLength);
    }
}

Output:

Average length of words starting with 'a': 5.0

Real-World Use Case

Calculating Average Age

In real-world applications, the averagingInt() method can be used to calculate the average age of a list of people.

Example

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

public class AverageAgeCalculator {
    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        int getAge() {
            return age;
        }
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35),
            new Person("David", 40)
        );

        // Calculate the average age of people
        double averageAge = people.stream()
                                  .collect(Collectors.averagingInt(Person::getAge));

        System.out.println("Average age: " + averageAge);
    }
}

Output:

Average age: 32.5

Conclusion

The Collectors.averagingInt() method is used to calculate the average of integer values in a stream. This method is particularly useful for computing the average of numeric properties of elements in a stream. By understanding and using this method, you can efficiently perform averaging operations in your Java applications.

Comments