本文共 2306 字,大约阅读时间需要 7 分钟。
在开发中,经常会有将 数据组装成为树形结构的场景,除了可以通过递归实现,还可以通过map 组装实现。
一,构造基本数据
import apple.laf.JRSUIUtils;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/**
* @创建人
* @创建时间 2020/5/25
* @描述
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TreeVo {
private int id;
private String name;
private int parent;
private List children;
public static List allTreeVoList() {
List list = Lists.newArrayList();
TreeVo heBeiTreeVo = TreeVo.builder().id(1).name("河北").parent(0).children(Lists.newArrayList()).build();
list.add(heBeiTreeVo);
TreeVo hanTreeVo = TreeVo.builder().id(2).name("邯郸").parent(1).children(Lists.newArrayList()).build();
list.add(hanTreeVo);
TreeVo weiTreeVo = TreeVo.builder().id(3).name("魏县").parent(2).children(Lists.newArrayList()).build();
list.add(weiTreeVo);
TreeVo beiTreeVo = TreeVo.builder().id(4).name("北京").parent(0).children(Lists.newArrayList()).build();
list.add(beiTreeVo);
TreeVo jingTreeVo = TreeVo.builder().id(5).name("北京市").parent(4).children(Lists.newArrayList()).build();
list.add(jingTreeVo);
TreeVo chaoTreeVo = TreeVo.builder().id(6).name("朝阳区").parent(5).children(Lists.newArrayList()).build();
list.add(chaoTreeVo);
return list;
}
}
二,通过map分组遍历
/**
* 组装树
*/
public void wrapperTreeTest() {
Gson gson = new Gson();
List list = TreeVo.allTreeVoList();
logger.info("结果是:{}", gson.toJson(list));
Map treeVoMap = list.stream().collect(Collectors.toMap(i -> i.getId(), i -> i));
//获取顶级树节点
List rootList = list.stream().filter(i -> !treeVoMap.containsKey(i.getParent())).collect(toList());
logger.info("rootList is:{}", gson.toJson(rootList));
for (TreeVo treeVo : list) {
if (treeVoMap.containsKey(treeVo.getParent())) {
TreeVo parentTree = treeVoMap.get(treeVo.getParent());
List children = parentTree.getChildren();
children.add(treeVo);
}
}
logger.info("最后树结构是:{}", gson.toJson(rootList));
}
三,结果是
[
{
"id":1,
"name":"河北",
"parent":0,
"children":[
{
"id":2,
"name":"邯郸",
"parent":1,
"children":[
{
"id":3,
"name":"魏县",
"parent":2,
"children":[
]
}
]
}
]
},
{
"id":4,
"name":"北京",
"parent":0,
"children":[
{
"id":5,
"name":"北京市",
"parent":4,
"children":[
{
"id":6,
"name":"朝阳区",
"parent":5,
"children":[
]
}
]
}
]
}
]
转载地址:http://oycpo.baihongyu.com/