我有一个person对象,该对象具有一个名称和一个地址列表作为参数。该地址具有街道,类型,城市和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"))
答案 0 :(得分:3)
您可以使用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;
}
}