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

前端 未结 5 1432
伪装坚强ぢ
伪装坚强ぢ 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:24

    Some of the other answers contain code that does a lot of linear searching through lists. I think the Java 8 Stream solution should not be much slower than the classical variant. So here is a solution that takes advantage of Streams without sacrificing much performance.

    List people = ...
    List regions = ...
    
    Map> zipToRegions =
        regions.stream().collect(
            () -> new HashMap<>(),
            (map, region) -> {
                for(String zipCode: region.getZipCodes()) {
                    List list = map.get(zipCode);
                    if(list == null) list = new ArrayList<>();
                    list.add(region);
                    map.put(zipCode, list);
                }
            },
            (m1, m2) -> m1.putAll(m2)
        );
    Map> personToRegions =
      people.stream().collect(
        Collectors.toMap(person -> person,
                         person -> zipToRegions.get(person.getZip()))
      );
    

提交回复
热议问题