importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjava.util.stream.Collectors;importorg.apache.commons.collections4.CollectionUtils;public classTreeUtils {/*** 普通list转树状list
*@paramtreeNodeList
*@return
*/
public static List list2Tree(ListtreeNodeList) {//Map> zoneByParentIdMap = treeNodeList.stream().collect(Collectors.groupingBy(TreeNode::getParentId));//treeNodeList.forEach(zone->zone.children = zoneByParentIdMap.get(zone.id));//return treeNodeList.stream().filter(v -> v.parentId.equals("0")).collect(Collectors.toList());
Map> nodeByParentIdMap =treeNodeList.stream().collect(Collectors.groupingBy(TreeNode::getParentId));
treeNodeList.forEach(node->node.setChildren(nodeByParentIdMap.get(node.getId())));return treeNodeList.stream().filter(v -> v.getParentId().equals("0")).collect(Collectors.toList());
}/*** 树状list转普通list
*@paramlist
*@return
*/
public static List tree2list(Listlist) {
List result = new ArrayList<>();for(TreeNode test : list) {
List c =test.getChildren();
result.add(test);if (!CollectionUtils.isEmpty(c)) {
result.addAll(tree2list(c));
test.setChildren(null);//}
}returnresult;
}public static voidmain(String[] args) {
List nodeList = new ArrayList<>();
nodeList.add(new TreeNode("10", "福建省","0", "FJS"));
nodeList.add(new TreeNode("11", "福州","10", "FZ"));
nodeList.add(new TreeNode("12", "莆田","10", "PT"));
nodeList.add(new TreeNode("13", "泉州","10", "QZ"));
nodeList.add(new TreeNode("14", "厦门","10", "XM"));
nodeList.add(new TreeNode("15", "龙岩","10", "LY"));
nodeList.add(new TreeNode("20", "浙江省","0", "ZJS"));
nodeList.add(new TreeNode("21", "杭州","20", "HZ"));
nodeList.add(new TreeNode("22", "嘉兴","20", "JX"));
nodeList.add(new TreeNode("23", "宁波","20", "NB"));
List treeList = TreeUtils.list2Tree(nodeList);
List list =TreeUtils.tree2list(treeList);
List treeList1 =TreeUtils.list2Tree(list);
}
}