【问题标题】:Collectors groupingBy based on City基于城市的收集器分组依据
【发布时间】:2019-04-29 13:40:37
【问题描述】:

我有一个人对象,它有一个名字和一个地址列表作为参数。地址有街道、类型、城市和 personId 我想按城市获取分组地图。我被卡住了

这是我目前的代码:

Map<String,List<Person>> MAP = personRepository.findAll().stream() 
         .collect(Collectors.groupingBy(person->person.getAddresses().stream()
         .map(address -> address.getCity())
         ."some kind of collector I assume"))

【问题讨论】:

    标签: java java-8 hashmap java-stream collectors


    【解决方案1】:

    您可以使用flatMap 来实现,可能是:

    Map<String, List<Person>> finalPersonMap = personRepository.findAll().stream()
                .flatMap(person -> person.getAddresses().stream()
                        .map(address -> new AbstractMap.SimpleEntry<>(address.getCity(), person)))
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    

    假设基本模型如下:

    static class Person {
        List<Address> addresses;
    
        List<Address> getAddresses() {
            return addresses;
        }
    }
    
    static class Address {
        String city;
    
        String getCity() {
            return city;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2018-10-12
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多