我有扁平物体 POJO:
class FamilyInformation {
String house;
String familyMember;
}
具有这样的数据:
[{
house: "houseName1",
familyMember: "Son"
},
{
house: "houseName1",
familyMember: "Mom"
},
{
house: "houseName1",
familyMember: "Dad"
}]
我想将其转换为分层对象 POJO:
class House {
String houseName;
List<FamilyMember> familyMembers;
}
class FamilyMember {
String familyMember;
}
我发现的所有信息都是将其转换为Map。但是我想让List<House>
包含List<FamilyMember>
任何想法,我该怎么办?
答案 0 :(得分:6)
尝试这个
Map<String,List<FamilyMember>> map = list
.stream()
.collect(
Collectors.groupingBy(
FamilyInformation::getHouseName,
Collectors.mapping(
family -> new FamilyMember(family.getFamilyMember()),
Collectors.toList()
)
)
);
然后
List<House> result = map.entrySet()
.stream()
.map(e -> new House(e.getKey(), e.getValue()))
.collect(Collectors.toList());
答案 1 :(得分:1)
这是非流版本:
首先,将house
分组,然后通过FamilyMember
+ forEach
映射到computeIfAbsent
:
Map<String, List<FamilyMember>> accumulator = new HashMap<>();
source.forEach(f -> accumulator.computeIfAbsent(f.getHouse(),
k -> new ArrayList<>()).add(new FamilyMember(f.getFamilyMember())));
然后从accumulator
获取每个条目并将其映射到House
对象:
List<House> result = new ArrayList<>();
accumulator.forEach((house, familyMembers) -> result.add(new House(house, familyMembers)));