[英]Java 8 Streams - Map Multiple Object of same type to a list using streams
[英]Java Streams: Create Map Using Multiple List of different object types
我想使用不同 object 類型的多個列表創建對象的 Map。 我想舉個例子,這樣會更清楚,更容易討論。
class Employee {
Long id;
String name;
// getters, setters, and toString
}
class Department {
Long id;
String name;
// getters, setters, and toString
}
class EmployeeDepartment {
Long id;
Long employeeId;
Long deptId;
// getters, setters, and toString
}
class Subject {
Long id;
String name;
// getters, setters, and toString
}
class EmployeeSubject {
Long id;
Long employeeId;
Long subjectId;
// getters, setters, and toString
}
我現在有
List<Employee> emplList;
List<EmployeeDepartment> emplDeptList;
List<EmployeeSubject> emplSubList;
我想獲得一個 Map ,我可以使用它來搜索員工:deptId 和 subjectId
就像是
Map<List<Long, Long>, List<Employee>> deptSubToEmpMap;
// representing Map<List<deptId, subId>, List<empl>>
// Or
Map<Long, Map<Long, List<Employee>> deptToSubToEmpMap;
// representing Map<deptId, Map<subId, List<empl>>
或任何其他方便的形式,如果它比上述表示更好。
注意:我是 Java Streams 的新手
您需要創建EmployeeSubjectDepartment
來保存員工、部門和主題之間的關系,如下所示,
@Getter@Setter
class EmployeeSubjectDepartment{
Long empId;
Long deptId;
Long subId;
public EmployeeSubjectDepartment(Long empId, Long deptId, Long subId) {
this.empId = empId;
this.deptId = deptId;
this.subId = subId;
}
}
然后合並emplDeptList
和emplSubList
得到emplyees
List<EmployeeSubjectDepartment> employeeSubjectDepartments = emplDeptList.stream()
.flatMap(dept -> emplSubList.stream()
.filter(sub -> dept.employeeId.equals(sub.employeeId))
.map(sub -> new EmployeeSubjectDepartment(dept.employeeId, dept.deptId, sub.subjectId)))
.collect(toList());
Map<Long, Map<Long, List<Long>>> result = employeeSubjectDepartments.stream()
.collect(groupingBy(EmployeeSubjectDepartment::getDeptId,
groupingBy(EmployeeSubjectDepartment::getSubId, mapping(e -> e.empId, toList()))));
這將導致Map
帶有員工 ID List
。
如果您想要員工List
,請創建EmployeeSubjectDepartment
,如下所示,
class EmployeeSubjectDepartment{
Employee emp;
Long deptId;
Long subId;
}
然后合並emplDeptList
和emplSubList
從emplList
獲取和 map 到emplyees
List<EmployeeSubjectDepartment> employeeSubjectDepartments = emplDeptList.stream()
.flatMap(dept -> emplSubList.stream()
.filter(sub -> dept.employeeId.equals(sub.employeeId))
.map(sub -> new EmployeeSubjectDepartment(emplList.stream().filter(e -> e.id == sub.employeeId).findAny().orElse(null), dept.deptId, sub.subjectId)))
.collect(toList());
Map<Long, Map<Long, List<Employee>>> result = employeeSubjectDepartments.stream()
.collect(groupingBy(EmployeeSubjectDepartment::getDeptId,
groupingBy(EmployeeSubjectDepartment::getSubId, mapping(e -> e.emp, toList()))));
這可能不是一個完美的解決方案,但您可以獲得所需的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.