我建议你实施equals
and hashcode
在你的Person
class.
Example:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
那么你可以有一个Map<Person, List<Address>>
作为结果集的接收者类型。
Map<Person, List<Address>> resultSet = findPerson.stream()
.collect(
Collectors.groupingBy(
Function.identity(),
Collectors.flatMapping(
p -> p.getAddress().stream(),
Collectors.toList()
)
)
)
;
该解决方案利用了flatMapping
收集器仅在 Java-9 中可用。
如果你仍在使用 Java-8 那么你可以这样做:
Map<Person, List<Address>> resultSet = findPerson.stream()
.collect(
Collectors.groupingBy(
Function.identity(),
Collectors.collectingAndThen(
Collectors.mapping(
Person::getAddress,
Collectors.toList()
),
lists -> lists.stream()
.flatMap(List::stream)
.collect( Collectors.toList() )
)
)
)
;
note- 事实上,我目前假设两个或更多人被认为是平等的name
and age
,但是,如果仅基于name
或者只是age
那么你需要调整equals
/ hashcode
方法一点点。