How to group elements of a List by elements of another in Java 8

前端 未结 5 1441
伪装坚强ぢ
伪装坚强ぢ 2021-02-16 00:09

I have the following problem: Given these classes,

class Person {
    private String zip;
    ...
    public String getZip(){
        return zip;
    }
}

class          


        
5条回答
  •  遇见更好的自我
    2021-02-16 00:30

    I have not done any testing of this code, but it compiles so it must be right (:eyeroll:).

    public Map> mapPeopleToRegion(List people, List regions){
        final Map> personToRegion = new HashMap<>();
        people.forEach(person ->
              personToRegion.put(
                    person,regions.stream().filter(
                          region -> region.getZipCodes().contains(person.getZip()))
                          .collect(Collectors.toList())));
        return personToRegion;
    }
    

提交回复
热议问题