如何通过使用Java流将平面对象转换为预期对象

时间:2019-01-03 12:55:38

标签: java java-8 java-stream

我有扁平物体 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>任何想法,我该怎么办?

2 个答案:

答案 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)));