Monday, January 31, 2022

Java Stream - Collectors.teeing() With Examples

In the Java Stream API, Collectors class implements Collector and provides many useful reduction operations like Collectors.groupingBy(), Collectors.partitioningBy(). There is also a Collectors.teeing() method added in Java 12 that takes two downstream Collectors as method argument and passes each stream element through these two downstream Collectors, there is also a third argument, a merging function that merges the results of both collectors into the final result.

It is a handy utility method for performing certain tasks where more processing is required with in a single method call.

Syntax of Collectors.teeing() method

Collector<T,?,R> teeing(Collector<? super T,?,R1> downstream1, Collector<? super T,?,R2> downstream2, BiFunction<? super R1,? super R2,R> merger)

Here parameters are-

  • downstream1- First downstream collector
  • downstream2- Second downstream collector
  • merger- Function which merges two results into a single one

Collectors.teeing() Java examples

1. If you want to get the average of numbers in a List. You can do that in a single method call by using Collectors.teeing(). First downstream Collector argument can do the job of counting elements, second Collector argument can do the job of getting the sum of elements and the merger operation can do the job of calculating average.

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

public class CollectorsTeeing {

  public static void main(String[] args) {
    List<Integer> numList = List.of(16, 27, 19, 75, 56);
    Double average = numList.stream().collect(Collectors.teeing(
        Collectors.counting(), Collectors.summingDouble(n -> n), 
        (count, sum) -> sum/count));
    System.out.println("Average of elements in the list- " + average);    

  }
}

Output

Average of elements in the list- 38.6

2. Using Collectors.teeing() method to get the employee with the maximum salary and employee with the minimum salary from the List of Employee objects.

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();
  }
}

Here first downstream collector gets the employee with max salary and the second downstream collector gets the employee with min salary. Merger function creates a list to store both employee objects.

public class CollectorsTeeing {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 24, "Mark", 'M', 9000), 
                new Employee("E004", 37, "Ritu", 'F', 11000),
                new Employee("E005", 32, "Anuj", 'M', 12000), 
        new Employee("E006", 28, "Amy", 'F', 14000)); 
    List<Optional<Employee>> list = empList.stream().collect(Collectors.teeing(
        Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)), 
                Collectors.minBy(Comparator.comparingInt(Employee::getSalary)), 
                   (emp1, emp2) -> {
                      List<Optional<Employee>> e = new ArrayList<>();
                        e.add(emp1);
                        e.add(emp2);
                        return e;
                   }));
    System.out.println("Employee with max salary- " + (list.get(0).isPresent()? list.get(0).get().getName():null));
    System.out.println("Employee with min salary- " + (list.get(1).isPresent()? list.get(1).get().getName():null));  

  }
}

Output

Employee with max salary- Amy
Employee with min salary- Ram

That's all for this topic Java Stream - Collectors.teeing() With Examples. 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.joining() With Examples
  2. Java Stream - Collectors.partitioningBy() With Examples
  3. Java Stream - Collectors.summingInt(), summingLong(), summingDouble()
  4. Java Stream - flatMap() With Examples
  5. Java Stream - Convert Stream to Set

You may also like-

  1. How to Get The Inserted ID (Generated ID) in JDBC
  2. Buffered Streams in Java IO
  3. Array in Java With Examples
  4. Java Program to Delete File And Directory Recursively
  5. Angular Reactive Form Validation Example
  6. Angular HttpClient - Set Response Type as Text
  7. Namespace And Variable Scope in Python
  8. Spring MVC Radiobutton And Radiobuttons Form Tag Example

No comments:

Post a Comment