Javaのストリームを使用して、リストの地図に一覧

ds2799:

私はクラスの会社を持っています

public class Company {

    private String companyid;

    private List<Employee> employees;
}

どのOne2Many関係で従業員に関連しています

public class Employee {

    private String employeeId;

    private Company company;

}

私は従業員のリストを与えていると私のようなマップを生成したいMap<companyId, List<Employee>>、それがパフォーマンスなければならないなどのJavaストリームを使用しています。

employees.stream().collect(
                  Collectors.groupingBy(Employee::getCompany, HashMap::new, Collectors.toCollection(ArrayList::new));

しかし、問題は、私は、従業員のようなものを呼び出すことはできません:: getCompany()である。getCompanyId()

これどうやってするの。任意の提案を歓迎します

彼らは次のとおりでした:

代わりに、メソッド参照のラムダ式を使用します。

Map<String,List<Employee> output =
    employees.stream()
             .collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId(), 
                                            HashMap::new, 
                                            Collectors.toCollection(ArrayList::new)));

それとも単に:

Map<String,List<Employee> output =
    employees.stream()
             .collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId()));

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=389886&siteId=1