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

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值