How to use Collectors.partitioningBy() in Java 8

18 total views, 1 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to use Collectors.partitioningBy() in Java 8.

If you would like to learn about Java 8 Stream operations.Please check out this link.

Collectors.partitioningBy() in Java 8

Collectors.partitioningBy() is a useful operation in Java stream which allows us to partition/group the elements in the stream based on a given predicate/boolean expression.Collectors.partitioningBy() will separate the stream of elements in two groups.

Collectors.partitioningBy() accepts a predicate function and returns a map with the key being a boolean type and value is the list of values of each boolean expression.

So, there are only two possible keys of the Collectors.partitioningBy() output i.e., true and false.

true -> (List of values)
false -> (List of values)

Collectors.partitioningBy() always returns a map of size 2(true and false).

Collectors.partitioningBy() Syntax

There are two variants of Collectors.partitioningBy() and let us see an example for each variant.

partitioningBy(Predicate<? super T> predicate)
Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.
partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)
Returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map<Boolean, D> whose values are the result of the downstream reduction.

Collectors.partitioningBy() examples(Variant 1)

The below example Collectors.partitioningBy() partition the stream of elements based on odd or even.

package com.scala;

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

public class StaticRef
{

    public static void main(String[] args)
    {
        List<Integer> fruits = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

        Map<Boolean, List<Integer>> partitonedResult = fruits.stream().collect(Collectors.partitioningBy(i -> i
                % 2 == 0));

        partitonedResult.forEach((key, value) -> {
            System.out.println("Key ->" + key);
            System.out.println("Value ->" + Arrays.toString(value.toArray()));
        });
    }
}

Output

Key ->false
Value ->[1, 3, 15, 17]
Key ->true
Value ->[2, 6, 8]

Another example which partition’s the stream of elements whether each element is greater than or equal to 10.

package com.scala;

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

public class StaticRef
{

    public static void main(String[] args)
    {
        List<Integer> fruits = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

        Map<Boolean, List<Integer>> partitonedResult = fruits.stream().collect(Collectors.partitioningBy(i -> i >= 10));

        partitonedResult.forEach((key, value) -> {
            System.out.println("Key ->" + key);
            System.out.println("Value ->" + Arrays.toString(value.toArray()));
        });
    }
}

Output

Key ->false
Value ->[1, 2, 3, 6, 8]
Key ->true
Value ->[15, 17]

Collectors.partitioningBy() examples(Variant 2)

The below Collectors.partitioningBy() example partition the stream of elements based on odd or even and gives us the count of each group by applying another Collector operation.

package com.scala;

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

public class StaticRef
{

    public static void main(String[] args)
    {
        List<Integer> fruits = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

        Map<Boolean, Long> partitonedResult = fruits.stream().collect(Collectors.partitioningBy(i -> i
                % 2 == 0, Collectors.counting()));

        partitonedResult.forEach((key, value) -> {
            System.out.println("Key ->" + key);
            System.out.println("Value ->" + value);
        });
    }
}

Output

Key ->false
Value ->4
Key ->true
Value ->3

Collectors.partitioningBy() example with Collectors.maxBy() and Collectors.minBy()

package com.scala;

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

public class StaticRef
{

    public static void main(String[] args)
    {
        List<Integer> fruits = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

        Map<Boolean, Optional<Integer>> partitonedResult = fruits.stream().collect(Collectors.partitioningBy(i -> i
                % 2 == 0, Collectors.maxBy(Integer::compareTo)));

        partitonedResult.forEach((key, value) -> {
            System.out.println("Key ->" + key);
            System.out.println("Value ->" + value.get());
        });
    }
}

Output

Key ->false
Value ->17
Key ->true
Value ->8
package com.scala;

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

public class StaticRef
{

    public static void main(String[] args)
    {
        List<Integer> fruits = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

        Map<Boolean, Optional<Integer>> partitonedResult = fruits.stream().collect(Collectors.partitioningBy(i -> i
                % 2 == 0, Collectors.minBy(Integer::compareTo)));

        partitonedResult.forEach((key, value) -> {
            System.out.println("Key ->" + key);
            System.out.println("Value ->" + value.get());
        });
    }
}

Output

Key ->false
Value ->1
Key ->true
Value ->2

References : Collectors.partitionBy() in Java 8

I hope you like this tutorial. Thanks for reading and Please leave us a comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.