簡體   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