当前位置: 首页 > 知识库问答 >
问题:

收集器按城市分组

梁俊智
2023-03-14

我有一个person对象,它有一个名称和一个地址列表作为参数。地址有一个街道,类型,城市,和个人我想获得一个按城市分组的地图。我卡住了

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"))

共有1个答案

何哲
2023-03-14

您可以使用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;
    }
}
 类似资料:
  • 例如,我如何使用类似这样的内容获得订阅类别等于的主题的观察者 多谢了。

  • 《城市点击器》是一款受 SimCity 启发的 Javascript 增量城市建设游戏。 你需要平衡住宅区、商业区和工业区及其税率,以发展特大城市(建议先建造一个)。

  • 一个城市选择的选择器,可以选择省份、城市。包含国内主要城市数据. [Code4App.com]

  • 特性 带有初始值 只能选择城市, 不可手工输入 使用默认城市列表 可指定name值, 可在直接form中使用 <label for="city">请选择城市</label> <input id="city" type="text" class="city" /> require(['moye/City', 'jquery'], function (City, $) { va

  • 定义 选择城市的组件。 图片展示 代码演示 import City from 'pile/dist/components/city' <City show={false} // cityArr={cityArr} // 城市数组 // position= {cityArr[0]} //定位城市 // 城市对象的默认属性为 // city_id、city_name、firs