繁体   English   中英

使用 Streams,查看列表是否包含来自另一个列表的 object 的属性

[英]Using Streams, see if a list contains a property of an object from another list

天哪,我几乎需要另一个帮助来回答这个问题,这里是新的 Java II 学生。 在此先感谢您的时间。

我有一个看起来像这样的员工列表:

public class Employee {
    private String name;
    private String department;
}

以及如下所示的公司列表:

public class Company {  
    private String name;    
    List<Department> departments;
}

部门只是:

public class Department{    
    private String name;
    private Integer totalSalary;
}

因此,我的任务是流式传输为同一家公司工作的员工列表。 (抱歉之前没有说:公司被传递给一个函数。这是唯一的论点)我第一次阅读时似乎很容易,但由于课程的设置方式,(公司只有一个部门列表,并且员工只有一个部门,但员工和公司之间没有联系)我可以 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 列出公司中的所有部门,但只是不知道如何将其带回来并将员工的部门字符串与来自属于该公司的部门...

List<Department> deptsInCompany = companies.stream()
                .filter(s -> s.getName().equals(passedInCompany))
                .flatMap(s -> s.getDepartments().stream())              
                .collect(Collectors.toList());

我只是不确定如何使用该部门列表来回溯并找到这些部门的员工。 我认为我的 ROOKIE 头脑无法摆脱想要每个部门 object 的员工列表,但没有!

任何小小的推动将不胜感激! 当我有一些技巧时,我会向 promise 付款!

假设您有一个所有员工的列表,并且您的所有 model 类的属性都有 getter,您可以执行以下操作:

public static void main(String[] args) {
    List<Company> companies = // Your list of Companies
    String passedInCompany = "Company";
    
    List<String> deptsNameInCompany = companies.stream()
            .filter(s -> s.getName().equals(passedInCompany))
            .flatMap(s -> s.getDepartments().stream())
            .map(Department::getName)
            .collect(Collectors.toList());

    List<Employee> employees = // All Employees
    List<Employee> employeesInCompanyDepts = employees.stream()
            .filter(employee -> deptsNameInCompany.contains(employee.getDepartment()))
            .collect(Collectors.toList());
}

基本上,您需要收集所有Department的名称,然后在其department属性中找到具有此类Department名称的Employee

将具有给定名称的(单个)公司的部门名称收集到一个Set中(查找比列表更快)。

Set<String> departmentNames = companies.stream()
    .filter(c -> c.getName().equals(companyName))
    .findFirst().get().getDepartments().stream()
    .map(Department::getName)
    .collect(Collectors.toSet());

然后从列表中删除不在这些部门中的所有员工。

employees.removeIf(e -> !departmentNames.contains(e.getDepartment()));

如果要保留员工列表,请过滤并收集:

List<Employee> employeesInCompany = employees.stream()
    .filter(e -> departmentNames.contains(e.getDepartment()))
    .collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM