java组装树形结构两种方式
返回实体
import lombok.Data;
@Data
public class IntentionVO {
/**
* id
*/
private Long id;
/**
* 父id
*/
private Long pid;
/**
* 名称
*/
private String name;
/**
* 子集
*/
private List<IntentionVO> children = new ArrayList<>();
sql
<select id="getIntentionAll" resultType="com.jd.aip.domain.knowledge.vo.IntentionVO">
select
ihci.id,
ihci.name,
ihci.parent_id as pid
from
intent_hierarchical_cate_info as ihci
where
ihci.yn = 1
order by ihci.id desc
</select>
逻辑层
public IntentionVO getListIntentionTree() {
//创建最顶部
IntentionVO vo = new IntentionVO();
vo.setId(-1L);
vo.setName("全部");
vo.setPid(null);
//获取所有意图集合
List<IntentionVO> data = knowledgeHomeDao.getIntentionAll();
if (CollectionUtils.isNotEmpty(data)) {
//组装树
List<IntentionVO> children = KnowledgeUtils.getChildrenGroupingStream(data);
//树集合
vo.setChildren(children);
}
return vo;
}
工具类
public class KnowledgeUtils {
/**
* 循环组装树(常规方式-数据量少时用)
*
* @param result 数据集合
* @return List<IntentionVO>
*/
public static List<IntentionVO> getChildren(List<IntentionVO> result) {
List<IntentionVO> treeListAll = new ArrayList<>();
//复制result数据
List<IntentionVO> treeList = new ArrayList<>(result);
// 遍历两次result来组装带有children关联性的对象,如果找到子级就删除List的数据
result.forEach(e -> {
for (IntentionVO en : result) {
//如果本级id与数据的父id相同,就说明是子父级关系
if (e.getId().longValue() == en.getPid().longValue()) {
e.getChildren().add(en);
treeList.remove(en);
}
}
});
return treeList ;
}
//------------------------------------------------------------------------------------------
/**
* 循环组装树(分组的方式-数据量大时用)
*
* @param result 数据集合
* @return List<IntentionVO>
*/
public static List<IntentionVO> getChildrenGroupingStream(List<IntentionVO> result) {
//根据父id分组
Map<Long, List<IntentionVO>> intentionMap = result.stream().collect(Collectors.groupingBy(IntentionVO::getPid));
//复制result数据
List<IntentionVO> treeList = new ArrayList<>(result);
//遍历result来组装带有children关联性的对象,如果找到子级就删除List的数据
for (IntentionVO intention : result) {
List<IntentionVO> children = intentionMap.get(intention.getId());
if (CollectionUtils.isNotEmpty(children)) {
intention.getChildren().addAll(children);
treeList.removeAll(children);
}
}
return treeList ;
}