Tuesday, January 25, 2022

Java Stream - Collectors.partitioningBy() With Examples

If you want to partition stream elements into two groups as per the given condition you can do that using partitioningBy() method of the java.util.stream.Collectors class.

Collectors.partitioningBy() method in Java

Collectors.partitioningBy() method partitions the input elements according to the passed Predicate argument and organizes them into a Map<Boolean, List<T>>. As you can notice the key in the Map is of type Boolean because the two keys used are “false” and “true” to map the input elements that doesn't pass the condition or pass it respectively.

There are two overloaded partitioningBy() method with Syntax as given below-

  • Collector<T,?,Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)- Partitions the stream elements according to the passed Predicate.
  • Collector<T,?,Map<Boolean,D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)- In this variant there is a Second argument of type Collector which reduces the values in each partition and organizes them into a Map<Boolean, D> whose values are the result of the downstream reduction.

Collectors.partitioningBy() Java examples

1. In this Collectors.partitioningBy() example we'll use it to partition a list of integers to return a map of even and odd numbers.

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

public class CollectorsPartitioning {

  public static void main(String[] args) {
    List<Integer> listOfNumbers = Arrays.asList(5,9,14,19,47,56,72,89,90,18);
      Map<Boolean, List<Integer>> numbers = listOfNumbers.stream()
                                 .collect(Collectors.partitioningBy(n -> n%2 == 0));
      // When key false - returns list with odd numbers
      System.out.println("Odd Numbers- " + numbers.get(false));
      // When key true - returns list with even numbers
      System.out.println("Even Numbers- " + numbers.get(true));
  }
}

Output

Odd Numbers- [5, 9, 19, 47, 89]
Even Numbers- [14, 56, 72, 90, 18]

2. Partition a List of Employee into those who earn more than 8000 and those who don’t using Collectors.partitioningBy() method.

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 CollectorsPartitioning {

  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));
      Map<Boolean, List<Employee>> numbers = empList.stream()
                                 .collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
      // When key false - employee with salary <= 8000
      System.out.println("Employees with Salary less than 8000- " + numbers.get(false));
      // When key true - employee with salary > 8000
      System.out.println("Employees with Salary greater than 8000- " + numbers.get(true));
  }
}

Output

Employees with Salary less than 8000- [Emp Id: E001 Name: Ram Age: 40, Emp Id: E002 Name: Shelly Age: 35, Emp Id: E005 Name: Anuj Age: 32]
Employees with Salary greater than 8000- [Emp Id: E003 Name: Mark Age: 24, Emp Id: E004 Name: Ritu Age: 37, Emp Id: E006 Name: Amy Age: 28]

3. In the second example we got the Employees partitioned into groups as per the condition salary greater than 8000 or not. Suppose you want the count of employees in each partitioned group, in that scenario you can use the Collectors.partitioningBy() method with two arguments and pass the second argument which is a counting Collector in this case.

public class CollectorsPartitioning {

  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));
      Map<Boolean, Long> numbers = empList.stream()
                                 .collect(Collectors.partitioningBy(e -> e.getSalary() > 8000, Collectors.counting()));
      // When key false - employee with salary <= 8000
      System.out.println("Count of employees with Salary less than 8000- " + numbers.get(false));
      // When key true - employee with salary > 8000
      System.out.println("Count of employees with Salary greater than 8000- " + numbers.get(true));
  }
}

Output

Count of employees with Salary less than 8000- 3
Count of employees with Salary greater than 8000- 3

That's all for this topic Java Stream - Collectors.partitioningBy() 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.groupingBy() With Examples
  2. Java Stream - Collectors.joining() With Examples
  3. Java Stream - noneMatch() With Examples
  4. Java Stream - skip() With Examples
  5. Java Stream - sorted() With Examples

You may also like-

  1. Transient Keyword in Java With Examples
  2. Executor And ExecutorService in Java With Examples
  3. Java Nested Class And Inner Class
  4. Java Exception Handling Interview Questions And Answers
  5. Deque Implementation in Java Using Doubly Linked List
  6. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  7. Angular Two-Way Data Binding With Examples
  8. Using Combiner in Hadoop MapReduce to Improve Performance

No comments:

Post a Comment