简体   繁体   English

如何根据对象的相同元素将集合拆分为多个 collections?

[英]How to split a collection into multiple collections based on the same elements of objects?

I have a collection where employees from all departments of the office are kept.我有一个收藏,用于保存办公室所有部门的员工。 I need to split this one collection into several different collections, that is, I want to split all employees into their departments.我需要把这个集合拆分成几个不同的collections,也就是我想把所有员工拆分到他们的部门。 It is important that I do not write the names of the departments myself, and the program itself breaks the collection into as many parts as necessary.重要的是我不自己写部门的名称,程序本身将集合分解为必要的多个部分。 Is it possible to do this, and if so, what would be the implementation?是否有可能做到这一点,如果可以,实施方式是什么?

There is a collection and this collection has office workers (all).有一个集合,这个集合有办公室工作人员(全部)。 The employee in the class has a registered department in which he works(Type STRING). class 中的员工有一个他工作的注册部门(类型 STRING)。 It is necessary to divide one entire collection based on the departments.有必要根据部门划分一个完整的集合。

To my regret I cannot share the classes (production code).令我遗憾的是,我无法共享课程(生产代码)。 I tried to run ArrayList through a for loop, and then split through an if, but then I got stuck and did not understand how other collections would then be created.我尝试通过 for 循环运行 ArrayList,然后通过 if 拆分,但后来我卡住了,不明白如何创建其他 collections。

Employee:员工:

public class Employee {

   private String name;

   private String lastName;

   private String department;
}

Method(where I spleet my lists):方法(我在哪里打扫我的列表):

public void method() { // Change method name

        List<EmployeeKnowledge> employeeKnowledgeList = employeeKnowledgeRepository
                .findEmployeeKnowledgeByStatus(KnowledgeStatus.KNOW);

        List<Employee> employeeList = new ArrayList<>(); // 
        employeeKnowledgeList.forEach(e -> employeeList.add(employeeRepository.getOne(e.getEmployeeId())));

        //AND NOW I DONT KNOW HOW SPLIT MY employeeList 
}

What you need here is a Map data structure, where the key will be the Department and the value will be a List<Employee> .您需要的是 Map 数据结构,其中键是Department ,值是List<Employee> This can be achieved very easily like so:这可以很容易地实现,如下所示:

var departmentMapped = employees
    .stream()
    .collect(Collectors.groupingBy(Employee::getDepartment));

Essentially what this does is to stream the list of employees and collect them to a new Map based on their respective department.本质上,这对 stream 的员工列表进行了处理,并将其收集到基于各自部门的新Map中。 With this on hand you can simply get the list of employees for a specific department using Map#get .有了这个,您可以使用Map#get简单地获取特定部门的员工列表。

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

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