使用Stream流遞歸 組合樹形結構


 

有一些需求,比如構建菜單,構建樹形結構,數據庫一般就使用父id來表示,為了降低數據庫的查詢壓力,我們可以一次性把數據查出來,然后使用Java8中的Stream流通過流式處理

實體類:Menu.java

import lombok.Builder;
import lombok.Data;

import java.util.List;

@Data
@Builder
public class Menu {
    /**
     * id
     */
    public Integer id;
    /**
     * 名稱
     */
    public String name;
    /**
     * 父id ,根節點為0
     */
    public Integer parentId;
    /**
     * 子節點信息
     */
    public List<Menu> childList;


    public Menu(Integer id, String name, Integer parentId) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
    }

    public Menu(Integer id, String name, Integer parentId, List<Menu> childList) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
        this.childList = childList;
    }

}

遞歸組裝樹形結構:

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        testtree();
    }

    public static void testtree() {
        //模擬從數據庫查詢出來
        List<Menu> menus = Arrays.asList(
                new Menu(1, "節點", 0),
                new Menu(2, "節點1", 1),
                new Menu(3, "節點1.1", 2),
                new Menu(4, "節點1.2", 2),
                new Menu(5, "節點1.3", 2),
                new Menu(6, "節點2", 1),
                new Menu(7, "節點2.1", 6),
                new Menu(8, "節點2.2", 6),
                new Menu(9, "節點2.2.1", 7),
                new Menu(10, "節點2.2.2", 7),
                new Menu(11, "節點3", 1),
                new Menu(12, "節點3.1", 11)
        );

        //獲取父節點
        List<Menu> collect = menus.stream()
                .filter(m -> m.getParentId() == 0)
                .peek(m -> m.setChildList(getChildrens(m, menus)))
                .collect(Collectors.toList());
        System.out.println(collect.toString());
    }

    /**
     * 遞歸查詢節點
     *
     * @param root 節點
     * @param all  所有節點
     * @return 節點信息
     */
    private static List<Menu> getChildrens(Menu root, List<Menu> all) {
        return all.stream()
                .filter(m -> Objects.equals(m.getParentId(), root.getId()))
                .peek(m -> m.setChildList(getChildrens(m, all)))
                .collect(Collectors.toList());
    }

}

結果:

 

 文章參考:https://blog.csdn.net/qq_19244927/article/details/106481777

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM