测试实体

    1. @Data
    2. public class Users {
    3. private int id;
    4. private int parentId;
    5. // 子节点数据
    6. private List<Users> child;
    7. public Users() {
    8. }
    9. public Users(int id, int parentId) {
    10. this.id = id;
    11. this.parentId = parentId;
    12. }
    13. @Override
    14. public String toString() {
    15. return "Users{" +
    16. "id=" + id +
    17. ", parentId=" + parentId +
    18. ", child=" + child +
    19. '}';
    20. }
    21. }

    实现功能的代码

    1. public class TestTree {
    2. public static void main(String[] args) {
    3. List<Users> list = new ArrayList<>();
    4. extracted(list);
    5. List<Users> results = new ArrayList<>();
    6. // 先获取一级节点
    7. List<Users> collect = list.stream().filter(v -> v.getParentId() == -1).collect(Collectors.toList());
    8. for (Users users : collect) {
    9. List<Users> childNodes = buildChildNode(users, list);
    10. users.setChild(childNodes);
    11. results.add(users);
    12. }
    13. System.out.println(results);
    14. }
    15. private static List<Users> buildChildNode(Users users, List<Users> list) {
    16. List<Users> childNodes = new ArrayList<>();
    17. int id = users.getId();
    18. List<Users> collect = list.stream().filter(v -> v.getParentId() == id).collect(Collectors.toList());
    19. if (collect == null || collect.size() == 0) {
    20. return childNodes;
    21. }
    22. for (Users users1 : collect) {
    23. childNodes.add(users1);
    24. List<Users> list1 = buildChildNode(users1, list);
    25. if (list1 != null && list1.size() > 0) {
    26. users1.setChild(list1);
    27. }
    28. }
    29. return childNodes;
    30. }
    31. /**
    32. 获取测试数据
    33. */
    34. private static void extracted(List<Users> list) {
    35. Users users1 = new Users(1, -1);
    36. list.add(users1);
    37. Users users11 = new Users(11, 1);
    38. list.add(users11);
    39. Users users12 = new Users(12, 1);
    40. list.add(users12);
    41. Users users2 = new Users(2, -1);
    42. list.add(users2);
    43. Users users21 = new Users(21, 2);
    44. list.add(users21);
    45. Users users22 = new Users(22, 2);
    46. list.add(users22);
    47. Users users211 = new Users(211, 21);
    48. list.add(users211);
    49. Users users212 = new Users(212, 21);
    50. list.add(users212);
    51. Users users3 = new Users(3, -1);
    52. list.add(users3);
    53. }
    54. }