Java8 Stream

一、前言

在日常开发中,必不可少的就是树形结构。有的时候可以使用Mybatis的ResultMap进行转化,有的时候需要进行Java进行手动转化为树结构。这里分享一个JDK8新特性Stream来实现List到树形结构的转化!

二、创建返回前端的实体类VO

  1. import lombok.Data;
  2. import java.util.List;
  3. /**
  4. * @date 2022/2/28 10:28
  5. */
  6. @Data
  7. public class NodeVO {
  8. private String id;
  9. private String name;
  10. private String pid;
  11. private List<NodeVO> children;
  12. public NodeVO(String id, String name, String pid) {
  13. this.id = id;
  14. this.name = name;
  15. this.pid = pid;
  16. }
  17. }

三、List转树形方法

  1. public static List<NodeVO> streamToTree(List<NodeVO> treeList, String parentId) {
  2. List<NodeVO> list = treeList.stream()
  3. // 过滤父节点
  4. .filter(parent -> parent.getPid().equals(parentId))
  5. // 把父节点children递归赋值成为子节点
  6. .map(child -> {
  7. child.setChildren(streamToTree(treeList,child.getId()));
  8. return child;
  9. }).collect(Collectors.toList());
  10. return list;
  11. }

四、测试

  1. public static void main(String[] args) {
  2. NodeVO NodeVO1 = new NodeVO("1","山东省","0");
  3. NodeVO NodeVO2 = new NodeVO("2","青岛市","1");
  4. NodeVO NodeVO3 = new NodeVO("3","市北区","2");
  5. NodeVO NodeVO4 = new NodeVO("4","济南市","1");
  6. NodeVO NodeVO5 = new NodeVO("5","浙江省","0");
  7. NodeVO NodeVO6 = new NodeVO("6","杭州市","5");
  8. NodeVO NodeVO7 = new NodeVO("7","西湖区","6");
  9. List<NodeVO> list = new ArrayList<>();
  10. list.add(NodeVO1);
  11. list.add(NodeVO2);
  12. list.add(NodeVO3);
  13. list.add(NodeVO4);
  14. list.add(NodeVO5);
  15. list.add(NodeVO6);
  16. list.add(NodeVO7);
  17. // 默认父节点id为0
  18. List<NodeVO> nodeVOList = streamToTree(list,"0");
  19. System.out.println(JSON.toJSONString(nodeVOList));
  20. }

结果展示:

  1. [
  2. {
  3. "children": [
  4. {
  5. "children": [
  6. {
  7. "children": [],
  8. "id": "3",
  9. "name": "市北区",
  10. "pid": "2"
  11. }
  12. ],
  13. "id": "2",
  14. "name": "青岛市",
  15. "pid": "1"
  16. },
  17. {
  18. "children": [],
  19. "id": "4",
  20. "name": "济南市",
  21. "pid": "1"
  22. }
  23. ],
  24. "id": "1",
  25. "name": "山东省",
  26. "pid": "0"
  27. },
  28. {
  29. "children": [
  30. {
  31. "children": [
  32. {
  33. "children": [],
  34. "id": "7",
  35. "name": "西湖区",
  36. "pid": "6"
  37. }
  38. ],
  39. "id": "6",
  40. "name": "杭州市",
  41. "pid": "5"
  42. }
  43. ],
  44. "id": "5",
  45. "name": "浙江省",
  46. "pid": "0"
  47. }
  48. ]