• Java list列表转Tree树形结构


    场景:有一个地区表

    CREATE TABLE `zone`  (
      `id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `parent_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

    实体类

    package com.springbootemaildemo.tree.zone;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Zone {
        String id;
        String name;
        String parentId;
        List<Zone> children;
    
        public Zone(String id, String name, String parentId) {
            this.id = id;
            this.name = name;
            this.parentId = parentId;
        }
    
        public void addChildren(Zone zone) {
            if (children == null) {
                children = new ArrayList<>();
            }
            children.add(zone);
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getParentId() {
            return parentId;
        }
    
        public void setParentId(String parentId) {
            this.parentId = parentId;
        }
    
        public List<Zone> getChildren() {
            return children;
        }
    
        public void setChildren(List<Zone> children) {
            this.children = children;
        }
    }

    工具类

    package com.springbootemaildemo.tree.zone;
    
    import org.apache.commons.collections4.CollectionUtils;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class ZoneUtils {
    
        /**
         * 方法一:两层循环
         *
         * @param zoneList
         * @return
         */
        public static List<Zone> buildTree2(List<Zone> zoneList) {
            List<Zone> result = new ArrayList<>();
            for (Zone zone : zoneList) {
                if (zone.parentId.equals("0")) {
                    result.add(zone);
                }
                for (Zone child : zoneList) {
                    if (child.parentId.equals(zone.id)) {
                        zone.addChildren(child);
                    }
                }
            }
            return result;
        }
    
        /**
         * 方法二 :两次遍历
         * 推荐使用方法二
         *
         * @param zoneList
         * @return
         */
        public static List<Zone> buildTree3(List<Zone> zoneList) {
            Map<String, List<Zone>> zoneByParentIdMap = new HashMap<>();
            zoneList.forEach(zone -> {
                List<Zone> children = zoneByParentIdMap.getOrDefault(zone.parentId, new ArrayList<>());
                children.add(zone);
                zoneByParentIdMap.put(zone.parentId, children);
            });
            zoneList.forEach(zone -> zone.children = zoneByParentIdMap.get(zone.id));
            return zoneList.stream()
                    .filter(v -> v.parentId.equals("0"))
                    .collect(Collectors.toList());
        }
    
        /**
         * 方法二 :使用java8的stream的方式
         * 推荐使用方法二
         *
         * @param zoneList
         * @return
         */
        public static List<Zone> buildTree3_01(List<Zone> zoneList) {
            Map<String, List<Zone>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
            zoneList.forEach(zone -> zone.children = zoneByParentIdMap.get(zone.id));
            return zoneList.stream().filter(v -> v.parentId.equals("0")).collect(Collectors.toList());
        }
    }

    测试类

    package com.springbootemaildemo.tree.zone;
    
    import com.alibaba.fastjson.JSON;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            List<Zone> zoneList = new ArrayList<>();
            zoneList.add(new Zone("1", "上海", "0"));
            zoneList.add(new Zone("2", "北京", "0"));
            zoneList.add(new Zone("3", "河南", "0"));
            zoneList.add(new Zone("31", "郑州", "3"));
            zoneList.add(new Zone("32", "洛阳", "3"));
            zoneList.add(new Zone("321", "洛龙", "32"));
            zoneList.add(new Zone("11", "松江", "1"));
            zoneList.add(new Zone("111", "泗泾", "11"));
            System.out.println("=======================2========================");
            List<Zone> rootZone2 = ZoneUtils.buildTree2(zoneList); // 测试第二种方法
            rootZone2.stream().forEach(item -> System.out.println(JSON.toJSONString(item)));
            System.out.println("===========================3====================");
            List<Zone> rootZone3 = ZoneUtils.buildTree3(zoneList); // 测试第三种方法
            rootZone3.stream().forEach(item -> System.out.println(JSON.toJSONString(item)));
            System.out.println("===========================4===================");
            List<Zone> rootZone3_01 = ZoneUtils.buildTree3_01(zoneList); // 测试第三种方法
            rootZone3_01.stream().forEach(item -> System.out.println(JSON.toJSONString(item)));
    
        }
    }

    树形结构如下:

     

  • 相关阅读:
    navicat 创建查询失败 can not create file
    使用Themeleaf时, HTML内嵌的JS代码需要注意< 和 >的问题
    window下查杀占用端口的进程
    Spring MVC的Rest URL 被错误解析成jsp, 导致404错误(XML方式下@Controller和@RestController需要配置<mvc:annotation-driving/>)
    一个本地DNS解析和mysql授权导致的Mysq连接失败问题(Access denied for user 'loan'@'kfcsdb1' (using password: YES))
    taglib报错The content of element type "taglib" must match "(tlib-version,...)
    cvc-complex-type.2.4.a: Invalid content was found starting with element 'display-name'
    在eclipse中运行spring web application时的异常: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    Spring3升级到Spring4时, 运行时出现找不到MappingJacksonHttpMessageConverter的情况
    如何在Spring MVC Test中避免”Circular view path” 异常
  • 原文地址:https://www.cnblogs.com/weigy/p/13193646.html
Copyright © 2020-2023  润新知