繁体   English   中英

收集者分组根据城市

[英]Collectors groupingBy based on City

我有一个人员对象,该人员对象具有名称和地址列表作为参数。 该地址具有街道,类型,城市和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"))

您可以使用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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM