ds2799 :
I have a class Company
public class Company {
private String companyid;
private List<Employee> employees;
}
Which is related to Employee in One2Many relationship
public class Employee {
private String employeeId;
private Company company;
}
I am supplied with a list of employees and I want to generate a map like Map<companyId, List<Employee>>
using java streams as it has to be performant.
employees.stream().collect(
Collectors.groupingBy(Employee::getCompany, HashMap::new, Collectors.toCollection(ArrayList::new));
But the problem is I can't call something like Employee::getCompany().getCompanyId()
How can I do this. Any suggestions are welcome
Eran :
Use a lambda expression instead of a method reference:
Map<String,List<Employee> output =
employees.stream()
.collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId(),
HashMap::new,
Collectors.toCollection(ArrayList::new)));
Or simply:
Map<String,List<Employee> output =
employees.stream()
.collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId()));
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=389295&siteId=1