Java Stream: divide into two lists by boolean predicate

后端 未结 4 2076
温柔的废话
温柔的废话 2020-12-01 13:54

I have a list of employees. They have isActive boolean field. I would like to divide employees into two lists: activeEmployees

4条回答
  •  青春惊慌失措
    2020-12-01 14:38

    What is the most sophisticated way?

    Java 12 of course with new Collectors::teeing

    List> 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
    

提交回复
热议问题