java list转tree_普通list和树状list互转

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:03   4325   0

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

}

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP