Stream Collectors - filtering

public static <T,​A,​R> Collector<T,​?,​R> filtering​(Predicate<? super T> predicate, Collector<? super T,​A,​R> downstream)

简单理解该方法的作用就是先对元素进行给定条件(第一个参数)的过滤,过滤后再对结果集进行转换(第二个参数)。

示例:

void test21() {

        List<Integer> list = List.of(2,5,8,9,4,20,11,43,55);

       

        List filterList = list.stream().collect(Collectors.filtering(a -> a>20, Collectors.toList()));

        filterList.stream().forEach(System.out::println);

    }

 

根据官网介绍,该方法一般配合groupingBy和partitioningBy去使用,官网示例:

Map<Department, Set<Employee>> wellPaidEmployeesByDepartment = employees.stream().collect(

     groupingBy(Employee::getDepartment, filtering(e -> e.getSalary() > 2000, toSet())));

以上代码简单理解,先使用groupingBy第一参数计算结果对元素进行分组,第一参数结果数据作为Map中的key,然后对分组结果进行filtering操作,filtering第一个参数是过滤条件,第二参数把过滤后结果数据保存的在Set中

最后把这个Set作为value保存在上面Map中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值