Java Stream:按布尔谓词划分为两个列表 [英] Java Stream: divide into two lists by boolean predicate

查看:393
本文介绍了Java Stream:按布尔谓词划分为两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有员工列表。他们有 isActive 布尔字段。我想将 employees 分成两个列表: activeEmployees formerEmployees 。是否可以使用Stream API?什么是最复杂的方法?

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?

推荐答案

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);






使用<$>有几个原因c $ c> partitioningBy over groupingBy (由 Juan Carlos Mendoza ):


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

首先, groupingBy 的参数是函数< Employee,Boolean> (在这种情况下),因此有可能向它传递一个可以返回null的函数,这意味着如果该函数返回null,则会有第3个分区任何员工。 partitioningBy 使用 Predicate< Employee> ,因此它只能返回2个分区。

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.

其次,您在结果地图中得到两个列表(*),其中 partitioningBy ;使用 groupingBy ,您只能获得元素映射到给定键的键/值对:

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: {}






(*) Java 8 Javadoc ,但它是为 Java 9

这篇关于Java Stream:按布尔谓词划分为两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆