0

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. 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). 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.

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 } 
0

1 Answer 1

2

What you need here is a Map data structure, where the key will be the Department and the value will be a 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. With this on hand you can simply get the list of employees for a specific department using Map#get.

Sign up to request clarification or add additional context in comments.

4 Comments

var? whats var?
var is a keyword introduced in Java 10, which allows for declaring variables by simply using var and letting local type inference, infer the type (based on the assignment of the right part). Think of var departmentMapped as Map<String, List<Employee>> departmentMapped.
I cannot get element. Please, tell me how?
What do you mean by I cannot get element? It a simple map object. Check on how you should retrieve a value from a Map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.