如何在java流中对groupBy应用过滤 [英] How to apply Filtering on groupBy in java streams

查看:1121
本文介绍了如何在java流中对groupBy应用过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何先分组,然后使用Java流应用过滤?

How do you group first and then apply filtering using Java streams?

示例:请考虑此员工 class:
我想按部门分组,列出一个薪水大于2000的员工。

Example: Consider this Employee class: I want to group by Department with a list of an employee having a salary greater than 2000.

public class Employee {
    private String department;
    private Integer salary;
    private String name;

    //getter and setter

    public Employee(String department, Integer salary, String name) {
        this.department = department;
        this.salary = salary;
        this.name = name;
    }
}   

我就是这样做的

List<Employee> list   = new ArrayList<>();
list.add(new Employee("A", 5000, "A1"));
list.add(new Employee("B", 1000, "B1"));
list.add(new Employee("C", 6000, "C1"));
list.add(new Employee("C", 7000, "C2"));

Map<String, List<Employee>> collect = list.stream()
    .filter(e -> e.getSalary() > 2000)
    .collect(Collectors.groupingBy(Employee::getDepartment));  

输出

{A=[Employee [department=A, salary=5000, name=A1]],
 C=[Employee [department=C, salary=6000, name=C1], Employee [department=C, salary=7000, name=C2]]}

因为那里B部门没有工资超过2000的员工。所以B部门没有钥匙:
但实际上,我想把那个钥匙放在空列表中 -

As there are no employees in Department B with a salary greater than 2000. So there is no key for Department B: But actually, I want to have that key with empty list –

预期产出

{A=[Employee [department=A, salary=5000, name=A1]],
 B=[],
 C=[Employee [department=C, salary=6000, name=C1], Employee [department=C, salary=7000, name=C2]]}

我们怎么做?

推荐答案

nullpointer的回答显示了直截了当的方式。如果您无法更新到Java 9,没问题,这个过滤收集器并不神奇。这是Java 8兼容版本:

nullpointer’s answer shows the straight-forward way to go. If you can’t update to Java 9, no problem, this filtering collector is no magic. Here is a Java 8 compatible version:

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

    BiConsumer<A, ? super T> accumulator = downstream.accumulator();
    return Collector.of(downstream.supplier(),
        (r, t) -> { if(predicate.test(t)) accumulator.accept(r, t); },
        downstream.combiner(), downstream.finisher(),
        downstream.characteristics().toArray(new Collector.Characteristics[0]));
}

您可以将它添加到您的代码库中,并以与Java 9相同的方式使用它如果你正在使用 import static ,那么你不必以任何方式更改代码。

You can add it to your codebase and use it the same way as Java 9’s counterpart, so you don’t have to change the code in any way, if you’re using import static.

这篇关于如何在java流中对groupBy应用过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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