91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java遞歸實現樹形結構的方式有哪些

發布時間:2022-10-26 09:57:55 來源:億速云 閱讀:187 作者:iii 欄目:開發技術

這篇文章主要介紹“Java遞歸實現樹形結構的方式有哪些”,在日常操作中,相信很多人在Java遞歸實現樹形結構的方式有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java遞歸實現樹形結構的方式有哪些”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

0、引言

在開發的過程中,很多業務場景需要一個樹形結構的結果集進行前端展示,也可以理解為是一個無限父子結構,常見的有報表指標結構、菜單結構等。Java中遞歸實現樹形結構的兩種常見方式如下:

  • Java7及以下純Java遞歸實現

  • Java8及以上借助lamda表達式實現

1、數據準備

Java實體類NodePO對應數據庫表

package com.wbs.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
public class NodePO {

    /**
     * 當前節點id
     */
    private String id;

    /**
     * 當前節點名稱
     */
    private String name;

    /**
     * 父級節點id
     */
    private String parentId;

    /**
     * 當前節點序號
     */
    private String orderNo;

    /**
     * 子集節點
     */
    private List<NodePO> children;

    /**
     * 構造函數
     * @param id
     * @param name
     * @param parentId
     * @param orderNo
     */
    public NodePO(String id,String name,String parentId,String orderNo){
        this.id = id;
        this.name = name;
        this.parentId = parentId;
        this.orderNo = orderNo;
    }
}

自己造一些數據模擬從數據庫中查詢出來的數據:

static final List<NodePO> nodePOs = Arrays.asList(
            new NodePO("1","一級節點1",null,"_0001"),
            new NodePO("2","二級節點1.1","1","_0002"),
            new NodePO("3","二級節點1.2","1","_0003"),

            new NodePO("4","一級節點2",null,"_0004"),
            new NodePO("5","二級節點2.1","4","_0005"),
            new NodePO("6","二級節點2.2","4","_0006"),
            new NodePO("7","三級節點2.2.1","6","_0007"),

            new NodePO("8","一級節點3",null,"_0008"),
            new NodePO("9","二級節點3.1","8","_0009"),
            new NodePO("10","三級節點3.1.1","9","_0010"),
            new NodePO("11","四級節點3.1.1.1","10","_0011"),
            new NodePO("12","五級節點3.1.1.1.1","11","_0012")
    );

2、類型轉化

從開發的過程中發現直接操作實體類集合,專門指定某一個實體類封裝的方法是不具有普適性的,所以將實體類集合統一轉化為Map集合,操作方便,具有一定的普適性:

List<Map<String, Object>> mapList = BeanMapUtils.listBeanToListMap(jsonObject);

BeanMapUtils自己簡單封裝一個工具類(不懼普適性勿噴):

package com.wbs.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import org.springframework.cglib.beans.BeanMap;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 一宿君
 * @version Id: BeanMapUtils.java, v 0.1 Administrator Exp $$
 * @date 2022-10-13 14:24:20
 * @desc java實體類和map相互轉換工具類
 */
public class BeanMapUtils {

    /**
     * 將實體類對象屬性轉化為map對象
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T t) {
        Map<String, Object> map = new HashMap<>();
        if (t != null) {
            if (t instanceof JSONObject){
                return (JSONObject)t;
            }
            BeanMap beanMap = BeanMap.create(t);
            for (Object key : beanMap.keySet()) {
                map.put(key.toString(), beanMap.get(key));
            }
        }
        return map;
    }


    /**
     * 將map對象中轉化為實體類對象
     * @param map
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T mapToBean(Map<String, Object> map,Class<T> clazz) throws Exception {
        T bean = clazz.newInstance();
        if (bean instanceof JSONObject){
            JSONObject jsonObject = (JSONObject)bean;
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                jsonObject.put(entry.getKey(),entry.getValue());
            }
            return (T)jsonObject;
        }
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 通過lambda表達式將List<JavaBean>轉化為List<Map<String, Object>>
     * @param objList
     * @param <T>
     * @return
     */
    public static <T> List<Map<String, Object>> listBeanToListMap(List<T> objList) {
        return objList.stream().map(new Function<T, Map<String, Object>>() {
            @Override
            public Map<String, Object> apply(T t) {
                Map<String,Object> map = Maps.newHashMap();
                if (t instanceof JSONObject){
                    return (JSONObject)t;
                }
                BeanMap beanMap = BeanMap.create(t);
                for (Object key : beanMap.keySet()) {
                    map.put(key.toString(), beanMap.get(key));
                }
                return map;
            }
        }).collect(Collectors.toList());
    }

    /**
     * 通過lambda表達式將List<Map<String, Object>>轉化為List<JavaBean>
     * @param mapList
     * @param <T>
     * @return
     */
    public static <T> List<T> listMapToListBean(List<Map<String,Object>> mapList,Class<T> clazz) {
        return mapList.stream().map(new Function<Map<String, Object>,T>() {
            @SneakyThrows
            @Override
            public T apply(Map<String, Object> map) {
                T t = clazz.newInstance();
                if (t instanceof JSONObject){
                    return (T)map;
                }
                BeanMap beanMap = BeanMap.create(t);
                beanMap.putAll(map);
                return t;
            }
        }).collect(Collectors.toList());
    }
}

其中org.springframework.cglib.beans.BeanMap;org.springframework:spring-core依賴下的工具包,spring-core核心依賴只要導入spring-boot-starter依賴即可

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.2.0.RELEASE</version>
</dependency>

Java遞歸實現樹形結構的方式有哪些

3、遞歸實現方法

3.1、Java7及以下純Java遞歸實現

既然是Java7及以下實現方式,那排序也用最原始的冒泡排序:

/**
     * 冒泡排序,小的在前,大的在后
     * @param list
     * @return
     */
    public static List<Map<String, Object>> sortJava7Map(List<Map<String, Object>> list){
        if(CollectionUtils.isEmpty(list)){
            return Lists.newArrayList();
        }
        boolean flag;
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            flag = false;
            for (int j = 1; j < size - i; j++) {
                Map<String, Object> frontMap = list.get(j - 1);
                Map<String, Object> afterMap = list.get(j);
                if (String.valueOf(frontMap.get("orderNo")).compareTo(String.valueOf(afterMap.get("orderNo"))) > 0){
                    list.set(j - 1,afterMap);
                    list.set(j,frontMap);
                    flag = true;
                }
            }
            //如果沒有發生位置互換,則退出循環
            if (!flag){
                break;
            }
        }
        return list;
    }

給定一個節點,獲取它的所有子節點:

/**
     * Java7及以下版本獲取子節點的方式
     * @param parentNode
     * @param allList
     * @return
     */
    public static List<Map<String, Object>> getJava7Children(Map<String,Object> parentNode,List<Map<String, Object>> allList){

        //存放當前節點的直系子節點
        List<Map<String, Object>> curNodeChildrenList = Lists.newArrayList();

        //存放直系子節點以外的節點
        List<Map<String, Object>> otherNodeList = Lists.newArrayList();

        Object pId = parentNode.get("id");
        for (Map<String, Object> map : allList) {
            Object curPId = map.get("parentId");
            if (ObjectUtils.isNotEmpty(curPId) && Objects.equals(pId,curPId)){
                curNodeChildrenList.add(map);
            }else {
                otherNodeList.add(map);
            }
        }
        if (curNodeChildrenList.isEmpty()){
            return curNodeChildrenList;
        }
        //每一層級都進行排序
        curNodeChildrenList = sortJava7Map(curNodeChildrenList);

        //迭代直系子節點再獲取子節點
        for (Map<String, Object> map : curNodeChildrenList) {
            map.put("children",getJava7Children(map,otherNodeList));
        }
        return curNodeChildrenList;
    }

給出一個結果集,構建樹形結果集:

/**
     * 使用Java7的方式獲取樹形結構
     * @param allList
     * @return
     */
    public static List<Map<String, Object>> getJava7ResultTree(List<Map<String, Object>> allList){
        //存放所有的一級節點
        List<Map<String, Object>> oneLevelNodeList = Lists.newArrayList();

        for (Map<String, Object> map : allList) {
            if (ObjectUtils.isEmpty(map.get("parentId"))){
                map.put("children",getJava7Children(map,allList));
                oneLevelNodeList.add(map);
            }
        }
        return sortJava8Map(oneLevelNodeList);
    }

獲取樹形結構:

//轉化為Map集合
List<Map<String, Object>> mapList = BeanMapUtils.listBeanToListMap(nodePOs);
//獲取樹形結構
List<Map<String, Object>> java7ResultTree = getJava7ResultTree(mapList);
//打印輸出
System.out.println(JSON.toJSONString(java7ResultTree));

打印結果:

[{"orderNo":"_0001","children":[{"orderNo":"_0002","children":[],"name":"二級節點1.1","id":"2","parentId":"1"},{"orderNo":"_0003","children":[],"name":"二級節點1.2","id":"3","parentId":"1"}],"name":"一級節點1","id":"1"},{"orderNo":"_0004","children":[{"orderNo":"_0005","children":[],"name":"二級節點2.1","id":"5","parentId":"4"},{"orderNo":"_0006","children":[{"orderNo":"_0007","children":[],"name":"三級節點2.2.1","id":"7","parentId":"6"}],"name":"二級節點2.2","id":"6","parentId":"4"}],"name":"一級節點2","id":"4"},{"orderNo":"_0008","children":[{"orderNo":"_0009","children":[{"orderNo":"_0010","children":[{"orderNo":"_0011","children":[{"orderNo":"_0012","children":[],"name":"五級節點3.1.1.1.1","id":"12","parentId":"11"}],"name":"四級節點3.1.1.1","id":"11","parentId":"10"}],"name":"三級節點3.1.1","id":"10","parentId":"9"}],"name":"二級節點3.1","id":"9","parentId":"8"}],"name":"一級節點3","id":"8"}]

樹形結構搞定!

3.2、Java8及以上借助lamda表達式實現

Java7的方式雖然實現了樹形結構,但是有一定的缺點,比如:代碼量比較大,邏輯相對較復雜,那Java8是如何簡化,如下所示:

既然Java8有lamda表達式,那代碼我們能省就省,先看排序,一行代碼搞定:

/**
     * 根據orderNo排序樹形結構的每一個層級
     * @param list
     * @return
     */
    public static List<Map<String, Object>> sortJava8Map(List<Map<String, Object>> list){
        if(CollectionUtils.isEmpty(list)){
            return Lists.newArrayList();
        }
        //關鍵之處,一行代碼搞定
        list.sort(Comparator.comparing(m -> String.valueOf(m.get("orderNo"))));
        return list;
    }

給定一個節點,獲取它的所有子節點:

釋義:
filter: 過濾,相當于for循環,再if條件判斷。
peek: 給定一個節點,往它的children塞子節點。

/**
     * 根據父級節點獲取所有的子集節點
     * @param parentNode
     * @param allList
     * @return
     */
    public static List<Map<String, Object>> getJava8Children(Map<String,Object> parentNode, List<Map<String, Object>> allList){
        return allList.stream()
                .filter(curNode -> ObjectUtils.isNotEmpty(curNode.get("parentId")) && Objects.equals(curNode.get("parentId"),parentNode.get("id")))
                .peek(m -> m.put("children", getJava8Children(m,allList))).collect(Collectors.toList());
    }

給出一個結果集,構建樹形結果集:

/**
     * 獲取樹形結構
     * @param mapList
     * @return treeList 樹形結果集
     */
    public static List<Map<String, Object>> getJava8ResultTree(List<Map<String, Object>> mapList){
        if (CollectionUtils.isEmpty(mapList)){
            return Lists.newArrayList();
        }
        //filter過濾出所有的一級節點
        return mapList.stream().filter(m -> Objects.equals(m.get("parentId"), null) || Objects.equals(m.get("parentId"), ""))
                .peek(m -> m.put("children", sortJava8Map(getJava8Children(m, mapList)))).collect(Collectors.toList());
    }

獲取樹形結構:

//轉化為Map集合
List<Map<String, Object>> mapList = BeanMapUtils.listBeanToListMap(nodePOs);
//獲取樹形結構
List<Map<String, Object>> java8ResultTree = getJava8ResultTree(mapList);
//打印輸出
System.out.println(JSON.toJSONString(java8ResultTree));

打印結果:

[{"orderNo":"_0001","children":[{"orderNo":"_0002","children":[],"name":"二級節點1.1","id":"2","parentId":"1"},{"orderNo":"_0003","children":[],"name":"二級節點1.2","id":"3","parentId":"1"}],"name":"一級節點1","id":"1"},{"orderNo":"_0004","children":[{"orderNo":"_0005","children":[],"name":"二級節點2.1","id":"5","parentId":"4"},{"orderNo":"_0006","children":[{"orderNo":"_0007","children":[],"name":"三級節點2.2.1","id":"7","parentId":"6"}],"name":"二級節點2.2","id":"6","parentId":"4"}],"name":"一級節點2","id":"4"},{"orderNo":"_0008","children":[{"orderNo":"_0009","children":[{"orderNo":"_0010","children":[{"orderNo":"_0011","children":[{"orderNo":"_0012","children":[],"name":"五級節點3.1.1.1.1","id":"12","parentId":"11"}],"name":"四級節點3.1.1.1","id":"11","parentId":"10"}],"name":"三級節點3.1.1","id":"10","parentId":"9"}],"name":"二級節點3.1","id":"9","parentId":"8"}],"name":"一級節點3","id":"8"}]

樹形結構搞定!兩種實現方式對比一下,你就說Java8的方式哇塞不哇塞!!!

到此,關于“Java遞歸實現樹形結構的方式有哪些”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

枣强县| 郯城县| 舞钢市| 平乐县| 即墨市| 屏南县| 西乌珠穆沁旗| 莱州市| 洛川县| 昌乐县| 宜州市| 班戈县| 苍梧县| 武宣县| 贵溪市| 永顺县| 铜鼓县| 萨迦县| 富民县| 农安县| 长子县| 翼城县| 平南县| 怀远县| 泽州县| 乌拉特后旗| 秀山| 临潭县| 盐津县| 米泉市| 台北县| 土默特左旗| 沅江市| 厦门市| 南丹县| 常德市| 大邑县| 宜城市| 尉氏县| 澄江县| 汪清县|