项目数据需要在后台拼装成树结构,所以写了两种方案来实现:
方案一:数据类型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; } } }