Java Stream: divide into two lists by boolean predicate

10,864

Solution 1

Collectors.partitioningBy:

Map<Boolean, List<Employee>> partitioned = 
    listOfEmployees.stream().collect(
        Collectors.partitioningBy(Employee::isActive));

The resulting map contains two lists, corresponding to whether or not the predicate was matched:

List<Employee> activeEmployees = partitioned.get(true);
List<Employee> formerEmployees = partitioned.get(false);

There are a couple of reasons to use partitioningBy over groupingBy (as suggested by Juan Carlos Mendoza):

Firstly, the parameter of groupingBy is a Function<Employee, Boolean> (in this case), and so there is a possibility of passing it a function which can return null, meaning there would be a 3rd partition if that function returns null for any of the employees. partitioningBy uses a Predicate<Employee>, so it can only ever return 2 partitions. which would result in a NullPointerException being thrown by the collector: whilst not documented explicitly, an exception is explicitly thrown for null keys, presumably because of the behavior of Map.computeIfAbsent that "If the function returns null no mapping is recorded", meaning elements would otherwise be dropped silently from the output. (Thanks to lczapski for pointing this out).

Secondly, you get two lists (*) in the resulting map with partitioningBy; with groupingBy, you only get key/value pairs where elements map to the given key:

System.out.println(
    Stream.empty().collect(Collectors.partitioningBy(a -> false)));
// Output: {false=[], true=[]}

System.out.println(
    Stream.empty().collect(Collectors.groupingBy(a -> false)));
// Output: {}

(*) This behavior isn't documented in the Java 8 Javadoc, but it was added for Java 9.

Solution 2

You can also use groupingBy in this case as there are 2 group posibilities (active and inactive employees):

Map<Boolean, List<Employee>> grouped = employees.stream()
                .collect(Collectors.groupingBy(Employee::isActive));

List<Employee> activeEmployees = grouped.get(true);
List<Employee> formerEmployees = grouped.get(false);

Solution 3

What is the most sophisticated way?

Java 12 of course with new Collectors::teeing

List<List<Employee>> divided = employees.stream().collect(
      Collectors.teeing(
              Collectors.filtering(Employee::isActive, Collectors.toList()),
              Collectors.filtering(Predicate.not(Employee::isActive), Collectors.toList()),
              List::of
      ));

System.out.println(divided.get(0));  //active
System.out.println(divided.get(1));  //inactive

Solution 4

If you are open to using a third-party library, this will work using Collectors2.partition from Eclipse Collections.

PartitionMutableList<Employee> partition =
        employees.stream().collect(
                Collectors2.partition(Employee::isActive, PartitionFastList::new));

List<Employee> activeEmployees = partition.getSelected();
List<Employee> formerEmployees = partition.getRejected();

You can also simplify things using ListIterate.

PartitionMutableList<Employee> partition =
        ListIterate.partition(employees, Employee::isActive);

List<Employee> activeEmployees = partition.getSelected();
List<Employee> formerEmployees = partition.getRejected();

PartitionMutableList is a type that extends from PartitionIterable. Every subtype of PartitionIterable has a collection for positive results getSelected() and negative results getRejected().

Note: I am a committer for Eclipse Collections.

Share:
10,864
Rudziankoŭ
Author by

Rudziankoŭ

Nice to meet you!

Updated on June 02, 2022

Comments

  • Rudziankoŭ
    Rudziankoŭ almost 2 years

    I have a list of employees. They have isActive boolean field. I would like to divide employees into two lists: activeEmployees and formerEmployees. Is it possible to do using Stream API? What is the most sophisticated way?