我有一个带有以下签名的Employee和EmployeeJob类:
public class Employee {
public Integer employeeId;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
}
public class EmployeeJob {
private Integer employeeJobId;
private Employee employee;
private String jobName;
public Integer getEmployeeJobId() {
return employeeJobId;
}
public void setEmployeeJobId(Integer employeeJobId) {
this.employeeJobId = employeeJobId;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
}
我想要一个Map<Integer, List<EmployeeJob>>
中的一个List<EmployeeJob>
,其中键是 Employee 类中的 employeeId 。我如何使用Java 8流按 employee-> employeeId 对该列表进行分组??
有可能在单个流中求解,还是应该以某种方式拆分它还是采用经典解决方案?
答案 0 :(得分:2)
使用Collectors.groupingBy
:
Map<Integer, List<EmployeeJob>> map =
list.stream()
.collect(Collectors.groupingBy(ej -> ej.getEmployee().getEmployeeId()));
答案 1 :(得分:0)
groupingBy()
正是这样做的:
Map<Integer, List<EmployeeJob>> map = jobs.stream().collect(groupingBy(job -> job.getEmployee().getEmployeeId()));
不幸的是,由于必须经过Employee
类,因此不能使用方法引用。
答案 2 :(得分:0)
public static void main(String[] args) {
List<EmployeeJob> listEmployees= new ArrayList<>();
System.out.println(listEmployees);//previous list
Map<Integer, List<EmployeeJob>> newMap =
listEmployees.stream()
.collect(Collectors.groupingBy(employee->employee.getEmployee().getEmployeeId()));
System.out.println(newMap); // new expected map
}