Java Collectors partitioningBy() Method

The partitioningBy() method in Java, part of the java.util.stream.Collectors class, is used to partition elements of a stream into two groups based on a given predicate. This method is useful when you need to divide elements into two categories based on a boolean condition.

Table of Contents

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

Introduction

The partitioningBy() method returns a Collector that partitions the input elements into two groups: those that match the predicate and those that do not. The result is a Map with boolean keys (true and false), each associated with a list of elements.

partitioningBy() Method Syntax

There are two overloaded versions of the partitioningBy() method:

  1. Basic partitioningBy() method:
public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)
  1. partitioningBy() method with a downstream collector:
public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T, A, D> downstream)

Parameters:

  • predicate: A Predicate that determines how the elements are partitioned.
  • downstream (optional): A Collector to be applied to the values associated with each key.

Returns:

  • A Collector that partitions the input elements.

Throws:

  • This method does not throw any exceptions.

Understanding partitioningBy()

The partitioningBy() method allows you to divide the elements of a stream into two groups based on a specified predicate. This is useful for scenarios where you need to separate elements into two categories, such as even and odd numbers or passing and failing grades.

Examples

Basic Usage

To demonstrate the basic usage of partitioningBy(), we will create a list of integers and partition them into even and odd numbers.

Example

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

public class PartitioningByExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Partition the numbers into even and odd
        Map<Boolean, List<Integer>> partitionedByEven = numbers.stream()
                                                               .collect(Collectors.partitioningBy(n -> n % 2 == 0));

        System.out.println("Even Numbers: " + partitionedByEven.get(true));
        System.out.println("Odd Numbers: " + partitionedByEven.get(false));
    }
}

Output:

Even Numbers: [2, 4, 6, 8, 10]
Odd Numbers: [1, 3, 5, 7, 9]

Using partitioningBy() with Downstream Collector

This example shows how to use partitioningBy() with a downstream collector to partition elements and then apply an additional collection operation, such as counting the number of elements in each group.

Example

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

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

        // Partition the words based on whether their length is greater than 4, and count the elements in each group
        Map<Boolean, Long> partitionedByLength = words.stream()
                                                      .collect(Collectors.partitioningBy(
                                                          word -> word.length() > 4,
                                                          Collectors.counting()
                                                      ));

        System.out.println("Words with length > 4: " + partitionedByLength.get(true));
        System.out.println("Words with length <= 4: " + partitionedByLength.get(false));
    }
}

Output:

Words with length > 4: 4
Words with length <= 4: 2

Real-World Use Case

Partitioning Students by Passing Grade

In real-world applications, the partitioningBy() method can be used to partition students based on whether they have passed or failed a course.

Example

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

public class PartitioningStudentsExample {
    static class Student {
        String name;
        int grade;

        Student(String name, int grade) {
            this.name = name;
            this.grade = grade;
        }

        boolean isPassing() {
            return grade >= 50;
        }

        @Override
        public String toString() {
            return name + " (" + grade + ")";
        }
    }

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 85),
            new Student("Bob", 45),
            new Student("Charlie", 75),
            new Student("David", 30),
            new Student("Eve", 60)
        );

        // Partition students based on whether they are passing
        Map<Boolean, List<Student>> partitionedByPassing = students.stream()
                                                                   .collect(Collectors.partitioningBy(Student::isPassing));

        System.out.println("Passing Students: " + partitionedByPassing.get(true));
        System.out.println("Failing Students: " + partitionedByPassing.get(false));
    }
}

Output:

Passing Students: [Alice (85), Charlie (75), Eve (60)]
Failing Students: [Bob (45), David (30)]

Conclusion

The Collectors.partitioningBy() method is used to partition elements of a stream into two groups based on a given predicate. This method is particularly useful for dividing elements into two categories based on a boolean condition. By understanding and using this method, you can efficiently manage partitioning operations in your Java applications.

Comments