How to Split a Java Collections using Predicate, Lambda and Steams


We can split a collection into multiple subcollections using a Predicate, Lambda, Streams and the Collectors.partitioningBy() method.


Example:

package org.code2care.examples;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class SplitCollectionByPredicateExample {

    public static void main(String... args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        Predicate<Integer> isEven = num -> num % 2 == 0;

        Map<Boolean, List<Integer>> evenOddMap = numbers.stream()
                .collect(Collectors.partitioningBy(isEven));

        List<Integer> evenNumbers = evenOddMap.get(true);
        List<Integer> oddNumbers = evenOddMap.get(false);
        
        System.out.println("Even Numbers: " + evenNumbers);
        System.out.println("Odd Numbers: " + oddNumbers);
    }
}
Output:

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


If you are working with Set then your code will be as follows.

Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

Predicate<Integer> isEven = num -> num % 2 == 0;

Set<Integer> evenNumbers = numbers.stream()
    .filter(isEven)
    .collect(Collectors.toSet());

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap