gpt4 book ai didi

java - 在 Java 8 中创建嵌套的父子列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:10:03 24 4
gpt4 key购买 nike

我是 Java 8 的新手,需要解决以下问题。

我有两个类如下:

class Person {
String name;
int age;
List<Address> address;
}

class Address {
String street;
String city;
String country;
}

现在我有一个来自数据库的列表,如下所示:

List<Person> findPerson;

adam
26
<123, xyz, yyy>

adam
26
<456, rrr, kkk>

bill
31
<666, uuu, hhh>

现在我需要将同一个人对象与不同地址对象合并为一个对象,如下所示?

List<Person> findPerson;

adam
26
<123, xyz, 456>
<456, rrr, 123>

bill
31
<666, uuu, 999>

这如何在 Java 8 流中完成?

最佳答案

我建议您实现 equalshashcode在你的Person类(class)。

例子:

@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() )
)
)
)
;

注意 - 照原样,我目前假设两个或更多人根据 name 被认为是平等的和 age , 但是,如果它仅基于 name或者只是 age那么你需要 tweek equals/hashcode一些方法。

关于java - 在 Java 8 中创建嵌套的父子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48603421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com