• 不用递归实现List转Tree


    缘由:能不递归就不递归

    代码实现Demo

    import com.alibaba.fastjson.JSON;
    import org.springframework.util.CollectionUtils;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class ListToTreeDemo {
    
        private static class Node {
            private int id;
            private int pid;
            private String name;
            private List<Node> child;
    
            public Node(int id, int pid) {
                this.id = id;
                this.pid = pid;
                this.name = "测试:"+ pid + ":" + id;
            }
    
            public int getId() {
                return id;
            }
    
            public void setId(int id) {
                this.id = id;
            }
    
            public int getPid() {
                return pid;
            }
    
            public void setPid(int pid) {
                this.pid = pid;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public List<Node> getChild() {
                return child;
            }
    
            public void setChild(List<Node> child) {
                this.child = child;
            }
        }
    
        public static void main(String[] args) {
    
            List<Node> nodes = new ArrayList<>();
            nodes.add(new Node(1, 0));
            nodes.add(new Node(2, 0));
            nodes.add(new Node(3, 0));
            nodes.add(new Node(4, 0));
            nodes.add(new Node(5, 1));
            nodes.add(new Node(6, 1));
            nodes.add(new Node(7, 2));
            nodes.add(new Node(8, 5));
            Map<Integer, List<Node>> collect = nodes.stream().collect(Collectors.groupingBy(Node::getPid));
    
            nodes.forEach((item) -> {
                if (CollectionUtils.isEmpty(collect.get(item.getId()))) {
                    item.setChild(new ArrayList<>());
                } else {
                    item.setChild(collect.get(item.getId()));
                }
            });
            List<Node> list = nodes
                    .stream()
                    .filter((item) -> item.getPid() == 0)
                    .collect(Collectors.toList());
    
            System.out.println(JSON.toJSONString(list));
        }
    }
    
    有三个字送给你,
    一是“诚”,
    二是“勤”,
    三是“专”。
    当你无比地想做成一件事,
    愿意为它倾尽无数心血和努力时,
    结果总不会太差。
  • 相关阅读:
    websocket --工作原理
    RabbitMQ
    django-缓存机制,form组件
    rabbitmq-安装
    学城项目
    django的orm--contenttype操作
    rest-framework序列化
    python模块与包
    python中的模块和包
    匿名函数python内置高阶函数以及递归
  • 原文地址:https://www.cnblogs.com/jarjune/p/14605487.html
Copyright © 2020-2023  润新知