java拼装树_java 数据拼装成树结构

这篇博客介绍了如何在Java中将数据拼装成树结构的两种方法。方案一涉及创建一个基类`BaseTreeVO`,并让需要转换的VO类继承它,然后使用工具类进行拼装。方案二同样是利用工具类`BaseTreeHelper`,但直接通过数据的父ID字段进行转换。博客提供了`BaseTreeHelper`的代码实现,包括两个静态方法,用于不同数据类型的转换。
摘要由CSDN通过智能技术生成

项目数据需要在后台拼装成树结构,所以写了两种方案来实现:

方案一:数据类型List

1>、首先增加树结构数据基础父类BaseTreeVO,然后需要拼装树结构的VO类需要继承来基础父类。

2>、创建并调用数据拼装数工具类

方案二:数据类型List>

调用工具类,传入标记父Id的字段

基础父类实现如下:

数据拼装树结构工具类如下: package com.xxxx.icop.framework.skeleton.template; import com.xxxx.icop.framework.skeleton.template.BaseTreeVO; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; public class BaseTreeHelper { private static final String KEY_CHILDREN = "children"; public BaseTreeHelper() { } public static List> createTree(List> data, String key) { if(CollectionUtils.isEmpty(data)) { return new ArrayList(); } else { Map groupByParentIdMap = (Map)data.stream().collect(Collectors.groupingBy((item) -> { return item.get(key) != null?item.get(key).toString():"nonParent"; })); Map dataMap = (Map)data.stream().collect(Collectors.toMap((item) -> { return item.get("id").toString(); }, (t2) -> { return t2; })); ArrayList resp = new ArrayList(); groupByParentIdMap.keySet().forEach((parentId) -> { if(dataMap.containsKey(parentId)) { Object child = (List)((Map)dataMap.get(parentId)).get("children"); if(CollectionUtils.isEmpty((Collection)child)) { child = new ArrayList(); ((Map)dataMap.get(parentId)).put("children", child); } ((List)child).addAll((Collection)groupByParentIdMap.get(parentId)); } else { resp.addAll((Collection)groupByParentIdMap.get(parentId)); } }); return resp; } } public static List createTree(List data) { if(CollectionUtils.isEmpty(data)) { return new ArrayList(); } else { Map groupByParentIdMap = (Map)data.stream().collect(Collectors.groupingBy((item) -> { return item.getParentId() != null?item.getParentId().toString():"nonParent"; })); Map dataMap = (Map)data.stream().collect(Collectors.toMap((item) -> { return item.getId().toString(); }, (t2) -> { return t2; })); ArrayList resp = new ArrayList(); groupByParentIdMap.keySet().forEach((parentId) -> { if(dataMap.containsKey(parentId)) { Object child = ((BaseTreeVO)dataMap.get(parentId)).getChildren(); if(CollectionUtils.isEmpty((Collection)child)) { child = new ArrayList(); } ((List)child).addAll((Collection)groupByParentIdMap.get(parentId)); ((BaseTreeVO)dataMap.get(parentId)).setChildren((List)child); } else { resp.addAll((Collection)groupByParentIdMap.get(parentId)); } }); return resp; } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值