package com.fayi.hutool.TreeUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User("1", "", "0", "手机"));
users.add(new User("2", "", "1", "小米"));
users.add(new User("3", "", "1", "华为"));
users.add(new User("4", "", "0", "水果"));
users.add(new User("5", "", "4", "香蕉"));
users.add(new User("6", "", "4", "菠萝"));
TreeNodeConfig config = new TreeNodeConfig();
List<Tree<String>> treeList = TreeUtil.build(users, "0", config, (treeNode, tree) -> {
tree.setId(treeNode.getId());
tree.setParentId(treeNode.getPid());
tree.setName(treeNode.getName());
});
System.out.println(JSONUtil.toJsonStr(treeList));
// 自定义字段名,userId 对应pid
users.clear();
users.add(new User("1", "10", "0", "手机"));
users.add(new User("2", "20", "10", "小米"));
users.add(new User("3", "30", "10", "华为"));
users.add(new User("4", "40", "0", "水果"));
users.add(new User("5", "50", "40", "香蕉"));
users.add(new User("6", "60", "40", "菠萝"));
config.setIdKey("userId");
treeList = TreeUtil.build(users, "0", config, (treeNode, tree) -> {
tree.setId(treeNode.getUserId());
tree.setParentId(treeNode.getPid());
tree.setName(treeNode.getName());
tree.putExtra("id", treeNode.getId());
});
System.out.println(JSONUtil.toJsonStr(treeList));
}
}
@NoArgsConstructor
@AllArgsConstructor
@Data
class User {
private String id;
private String userId;
private String pid;
private String name;
}
可以灵活配置,树形结果返回,不再需要自己写递归了