我有一个列表,其中包含Employee类的对象,其他列表中包含Department类的对象,如下所示:-
Class Employee {
String emolpyee_id;
String employee_Name;
}
Class Dapartment {
String emolpyee_id;
String employee_Department;
}
List<Employee> empl = = new ArrayList<>();
List<Dapartment> depart = = new ArrayList<>();
Employee e1 = new Employee("12","Testing");
Employee e2 = new Employee("16","TestingOthers");
Dapartment d1 = new Dapartment("12","IT");
Dapartment d2 = new Dapartment("12","Networking");
Dapartment d3 = new Dapartment("12","Financing");
Dapartment d4 = new Dapartment("16","IT");
Dapartment d5 = new Dapartment("16","Networking");
empl.add(e1);
empl.add(e2);
depart.add(d1);
depart.add(d2);
depart.add(d3);
depart.add(d4);
depart.add(d5);
Class ExpectedResult {
String emolpyee_id;
String employee_Name;
List<String> employee_Department;
}
List<ExpectedResult> expResult = {{"12","Testing",{"IT","Networking","Financing"}} ,{"16","TestingOthers",{"IT","Networking"}}}
我知道我们可以使用普通的for循环执行此操作,但我想使用lambda和Java 8流实现此输出。
答案 0 :(得分:1)
首先使用groupingBy将List<Department>
流到Map<String,List<String>>
中,groupingBy是员工ID作为键的映射,而值是部门列表
Map<String, List<String>> groupby = depart.stream().
collect(Collectors.groupingBy(Department::getEmolpyee_id, Collectors.mapping(Department::getEmployee_Department, Collectors.toList())));
然后为List<Employee>
中的每个对象获取Map
中的部门
List<ExpectedResult> expected = empl.stream().
map(emp-> new ExpectedResult(emp.getEmolpyee_id(),emp.getEmployee_Name(),groupby.get(emp.getEmolpyee_id()))).collect(Collectors.toList());
注意,如果分组依据List<String> employee_Department;
不包含员工ID和值,则ExpectedResult
中的Map
可能为空
侧面注释: class
是小写的Class
错误,并且部门的拼写更正