java 复制树_java不需要递归列表转树形结构

@return 返回树结构数据

*/

public static

List

listToTree(List

treeNodeList, Long rootId, int rootType) {

// 储存根节点集合

List

baseNodes = new ArrayList<>();

// 节点id->对应的节点

HashMap sonMap = new HashMap<>(baseNodes.size());

// 节点id->节点对应的子节点

HashMap

> parentMap = new HashMap<>(baseNodes.size());

for (T currentNode : treeNodeList) {

Long currentId = currentNode.getId();

Long parentId = currentNode.getParentId();

// 把节点先放在Map中,为了以后获取当前节点的父节点

sonMap.put(currentId, currentNode);

if (parentMap.get(parentId) == null) {

parentMap.put(parentId, new ArrayList<>());

}

//将子节点加入父节点

parentMap.get(parentId).add(currentNode);

// 判断当前节点是否有父节点

if (sonMap.get(parentId) != null) {

if (sonMap.get(parentId).getChildrenList() == null) {

sonMap.get(parentId).setChildrenList(new ArrayList<>());

}

// 将当前节点添加到父节点中

sonMap.get(parentId).getChildrenList().add(currentNode);

}

// 判断当前节点是否有子节点

if (!CollectionUtils.isEmpty(parentMap.get(currentId))) {

//将所有的子节点加入到当前节点

currentNode.setChildrenList(parentMap.get(currentId));

}

//根据节点id过滤根节点

if (rootType == 1 && currentNode.getId().longValue() == rootId.longValue()) {

baseNodes.add(currentNode);

}

//根据父节点id过滤根节点

if (rootType == 2 && currentNode.getParentId().longValue() == rootId.longValue()) {

baseNodes.add(currentNode);

}

}

return baseNodes;

}

』测试类public class TreeToListTest {

@Test

public void test() throws Exception {

List

treeNodes=new ArrayList<>();

treeNodes.add(createNode(1L,0L));

treeNodes.add(createNode(2L,10L));

treeNodes.add(createNode(3L,11L));

treeNodes.add(createNode(4L,3L));

treeNodes.add(createNode(5L,3L));

treeNodes.add(createNode(6L,31L));

treeNodes.add(createNode(7L,13L));

treeNodes.add(createNode(8L,2L));

treeNodes.add(createNode(9L,2L));

treeNodes.add(createNode(10L,1L));

treeNodes.add(createNode(11L,1L));

treeNodes.add(createNode(12L,1L));

treeNodes.add(createNode(13L,1L));

List

treeNodeList1=TreeNodeUtil.listToTree(treeNodes,1L,1);

}

』`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值