【问题标题】:Using Streams, see if a list contains a property of an object from another list使用 Streams,查看列表是否包含来自另一个列表的对象的属性
【发布时间】:2022-01-18 05:29:37
【问题描述】:

天啊,我几乎需要一点帮助来回答这个问题!新的 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;
}

因此,我的任务是流式传输为同一家公司工作的员工列表。 (抱歉之前没有说:公司被传递给一个函数。这是唯一的论点)我第一次阅读时似乎很容易,但由于课程的设置方式,(公司只有一个部门列表,并且员工只有一个部门,但员工和公司之间没有链接属于该公司的部门...

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

我只是不确定如何使用该部门列表来回溯并找到这些部门的员工。我认为我的 ROOKIE 头脑无法忘记每个部门对象中都有一个员工列表,但没有!

任何小小的推动将不胜感激!我保证当我有技巧的时候付钱!!

【问题讨论】:

  • 你有所有员工的名单吗?
  • 您究竟是什么意思流式传输为同一家公司工作的员工列表?哪间公司?一个具体的?或者创建公司地图到员工列表? “流媒体”是什么意思?你想用流做什么?如果您没有从流中得到结果,则流什么也不做。
  • 你快到了。无需将部门流收集到列表中,您只需将其重新映射到.flatMap(d -&gt; employees.stream().filter(e -&gt; d.getName().equals(e.getDepartment()))) 等员工流中,然后收集员工列表

标签: java list collections stream


【解决方案1】:

将具有给定名称的(单个)公司的部门名称收集到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());

【讨论】:

    【解决方案2】:

    假设您有一个所有员工的列表,并且您的所有模型类的属性都有 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());
    }
    

    基本上你需要收集所有Departments 名称,然后在其department 属性中找到具有Department 名称的Employees。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2022-01-23
      • 2012-07-04
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多