树对象的类定义如下
@Setter
@Getter
public class TreeDto {
private Integer id;
private String name;
private Integer parentId;
}
生成树的方法代码
public static List<TreeDto> buildTreeParallel(List<? extends TreeDto> list) {
List<TreeDto> result = new ArrayList<>();
Map<Integer, TreeDto> map = new HashMap<>(list.size());
list.forEach(e -> map.put(e.getId(), e));
Set<? extends Map.Entry<Integer, ? extends TreeDto>> entries = map.entrySet();
entries.parallelStream().forEach(entry -> {
TreeDto value = entry.getValue();
if (value != null) {
TreeDto treeDto = map.get(value.getParentId());
if (treeDto != null) {
List<TreeDto> children = treeDto.getChildren();
if (children == null) {
children = new ArrayList<>();
treeDto.setChildren(children);
}
children.add(value);
treeDto.setChildrenCount(children.size());
} else {
result.add(value);
}
}
});
return result;
}