通过stream实现list转tree方法
1:前言
这个大概能被称为通用方法吧,代码比较简单。
需要jdk8,毕竟stream()是8开始有的。
创建对象:
对象必须有上下级联系的字段,如:id 和 parentId
@Data
public class TreeModel {
/**
* 名称
**/
private String name;
/**
* id
**/
private Long id;
/**
* 父级id
**/
private Long parentId;
/**
* 子级列表
**/
private List<TreeModel> children;
public TreeModel(Long id, String name,Long parentId) {
this.name = name;
this.id = id;
this.parentId = parentId;
}
public TreeModel(Long id, String name) {
this.name = name;
this.id = id;
this.parentId = null;
}
}
2:TreeDemo实现类
最重要的方法getTree()中,filter()方法里的三元判断有这部分:
parentId == node.getParentId(),是考虑到最顶级对象的parentId为null的情况。
public class TreeDemo {
public static void main(String[] args) {
//获取模拟数据
List<TreeModel> list = getListModel();
//转成SONString,方便格式化
String str = JSONObject.toJSONString(getTree(list,null));
System.out.println("result = "+str);
}
//**********最重要的方法*******************
public static List<TreeModel> getTree(List<TreeModel> list, Long parentId) {
List<TreeModel> result = list
.stream()
.filter(node -> null == parentId ? parentId == node.getParentId() : parentId.equals(node.getParentId()))
.map(node -> {
node.setChildren(getTree(list, node.getId()));
return node;
})
.collect(Collectors.toList());
return result;
}
//模拟数据 自身id,自身名称,父级id(可为null),具体见TreeModel的构造方法
public static List<TreeModel> getListModel(){
List<TreeModel> list = new LinkedList<>();
list.add(new TreeModel(1L,"测试1"));
list.add(new TreeModel(2L,"测试2"));
list.add(new TreeModel(3L,"测试3",1L));
list.add(new TreeModel(4L,"测试4",1L));
list.add(new TreeModel(5L,"测试5",3L));
list.add(new TreeModel(6L,"测试6",5L));
list.add(new TreeModel(7L,"测试7",2L));
list.add(new TreeModel(8L,"测试8",7L));
return list;
}
}
3:将结果json格式化
[
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"id": 6,
"name": "测试1",
"parentId": 5
}
],
"id": 5,
"name": "测试1",
"parentId": 3
}
],
"id": 3,
"name": "测试1",
"parentId": 1
},
{
"children": [],
"id": 4,
"name": "测试1",
"parentId": 1
}
],
"id": 1,
"name": "测试1"
},
{
"children": [
{
"children": [
{
"children": [],
"id": 8,
"name": "测试1",
"parentId": 7
}
],
"id": 7,
"name": "测试1",
"parentId": 2
}
],
"id": 2,
"name": "测试1"
}
]