Java Stream: split into two lists by logical predicate

I have a list employees. They have a isActiveboolean field. I would like to split employeesinto two lists: activeEmployeesand formerEmployees. Can I use the Stream API? What is the hardest way?

+11
source share
4 answers

Collectors.partitioningBy:

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

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

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

There are several reasons to use partitioningByinstead groupingBy(as suggested by Juan Carlos Mendoza ):

-, groupingBy Function<Employee, Boolean> ( ), , , , 3- , . partitioningBy Predicate<Employee>, 2 ., , NullPointerException : , , - Map.computeIfAbsent, " , ", , . ( lczapski ).

-, (*) partitioningBy; groupingBy /, :

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

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

(*) Java 8 Javadoc, Java 9.

+16

groupingBy , ( ):

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

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

, Collectors2.partition Eclipse Collections.

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

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

, ListIterate.

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

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

PartitionMutableList - , PartitionIterable. PartitionIterable getSelected() getRejected().

Note: I am a committer for Eclipse Collections.

+2
source

  What is the hardest way?

Java 12 of course with the new Collectors::teeing

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

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

Source: https://habr.com/ru/post/1688231/


All Articles