假设数据表如下所示:
Map<Integer, Integer> childToParent = new HashMap<>();
childToParent.put(1, 1);
childToParent.put(2, 1);
childToParent.put(3, 1);
childToParent.put(4, 2);
childToParent.put(5, 2);
我们可以创建一个父子映射:
Map<Integer, List<Integer>> parentToChildren = childToParent.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
为简单起见,我们同样创建一个Company 类:
@Data
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Company {
private final int id;
@JsonProperty(value = "child")
private List<Company> children;
}
然后创建Company对象:
Map<Integer, Company> idToCompany = childToParent.keySet().stream()
.map(integer -> new Company(integer, null))
.collect(Collectors.toMap(Company::getId, company -> company));
现在我们可以为每个父母设置孩子:
idToCompany.values().forEach(company -> {
List<Integer> childrenIds = parentToChildren.get(company.getId());
if(childrenIds != null){
List<Company> children = childrenIds.stream()
.filter(childId -> childId != company.getId()) // a company can't be a parent of itself
.map(idToCompany::get)
.collect(Collectors.toList());
company.setChildren(children);
}
});
现在我们可以像这样提取“头部”公司:
List<Company> companiesHeads = childToParent.entrySet().stream()
.filter(childIdToParentId -> childIdToParentId.getKey().equals(childIdToParentId.getValue()))
.map(Map.Entry::getKey)
.map(idToCompany::get)
.collect(Collectors.toList());
并以 JSON 格式打印到屏幕上:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(companiesHeads));
输出:
[ {
"id" : 1,
"child" : [ {
"id" : 2,
"child" : [ {
"id" : 4
}, {
"id" : 5
} ]
}, {
"id" : 3
} ]
} ]