本文主要是介绍java_扁平<--->树转换的思路和方法参考,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
扁平转树形笔记
1.通过先找到根节点,然后在递归子节点的方法找子节点的子节点
public static List<Good> list2tree(List<Good> list){List<Good> resList = new ArrayList<>();for (Good good : list) {// 找到根节点if (good.getpId() == 0){Good root = getChild(good, list);resList.add(root);}}return resList;}// 找子节点方法public static Good getChild(Good parentNode,List<Good> list){for (Good good : list) {if (good.getpId() == parentNode.getId()){if (parentNode.getChildren() == null){parentNode.setChildren(new ArrayList<>());}parentNode.getChildren().add(getChild(good, list));}}return parentNode;}
2.利用map集合的特性,将pid相同的元素归类到同一集合中用map存储pid为键元素集合为值
public static List<Good> list2treeForMap(List<Good> list){// 通过相同的父节点,将数据分类Map<Integer,List<Good>> mapForPid = list.stream().collect(Collectors.groupingBy(good -> good.getpId()));// 遍历传入的集合List<Good> res = new ArrayList<Good>();for (Good good : list) {if (good.getpId() == 0){ // 根节点res.add(good);}// 获取通过id获取子节点数据List<Good> goodList = mapForPid.get(good.getId());if (goodList != null && goodList.size() > 0) { // 有子节点if (good.getChildren() == null){good.setChildren(new ArrayList<>());}good.setChildren(goodList);}}return res;}
树形转扁平
public static List<Good> tree2list(List<Good> treeList){List<Good> resList = new ArrayList<>();for (Good good : treeList) {if (good.getChildren() != null && good.getChildren().size() > 0){resList.addAll(tree2list(good.getChildren()));}good.setChildren(null);resList.add(good);}return resList;}
}
这篇关于java_扁平<--->树转换的思路和方法参考的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!