Friday, April 22, 2022

Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()

Collectors Class in Java Stream API provides many useful utility methods that can be used with Java Streams. One such group of methods, which can be classified as Collectors.averaging methods produces the arithmetic mean of the stream elements. There are following averaging methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)- This method is used to get average of stream of integers. If no elements are present, the result is 0.
  2. public static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)- This method is used to get average of stream of longs. If no elements are present, the result is 0.
  3. public static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get average of stream of doubles. If no elements are present, the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implemented to extract the property to be averaged meaning their implementation produces a int-valued, long-valued and double-valued result respectively.

Collectors.averagingInt() Java example

In this example we’ll get the average of the List elements where elements are of type Integer.

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

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Integer> numbers = Arrays.asList(16, 17, 32, 5, 3);
      double avg = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingLong() Java example

In this example we’ll get the average of the List elements where elements are of type long.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Long> numbers = Arrays.asList(16L, 17L, 32L, 5L, 3L);
      double avg = numbers.stream().collect(Collectors.averagingLong(Long::longValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingDouble() Java example

In this example we’ll get the average of the List elements where elements are of type double.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Double> numbers = Arrays.asList(16.87, 17.34, 23.45, 2.22, 3.67);
      double avg = numbers.stream().collect(Collectors.averagingDouble(Double::doubleValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 12.709999999999999

Collectors.averagingInt with Custom Object Example

In this example we’ll use summing method to get the average of salaries for all the employees.

Employee Class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class CollectorAveraging {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
     double avg = empList.stream().collect(Collectors.averagingInt(Employee::getSalary));
     System.out.println("Average employee salary- " + avg);
  }
}

Output

Average employee salary- 8833.333333333334

That's all for this topic Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble(). If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Collectors.summingInt(), summingLong(), summingDouble()
  2. Java Stream - Collectors.joining() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - noneMatch() With Examples
  5. Java Stream - limit() With Examples

You may also like-

  1. Reflection in Java - Getting Constructor Information
  2. Serialization Proxy Pattern in Java
  3. StringJoiner Class in Java With Examples
  4. Binary Tree Traversal Using Breadth First Search Java Program
  5. Java Collections Interview Questions And Answers
  6. Installing Anaconda Distribution On Windows
  7. Autowiring in Spring Using XML Configuration
  8. Spring Batch Processing With List of Objects in batchUpdate() Method

No comments:

Post a Comment