Java汎用再帰構築ツリーの使用

15050 ワード

ツリーエンティティの定義
@Data
public class Tree<T> {
    /**
     *   ID
     */
    private String id;
    /**
     *       
     */
    private List<Tree<T>> children = new ArrayList<>();

    /**
     *  ID
     */
    private String parentId;
     /**
     *       
     */
    private String text;

ツリーツールクラス
package com.yl.util.tree;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {

   /**
    *         
    *
    * @param modules
    * @return
    */
   public static <T> List<Tree<T>> buildByRecursive(List<Tree<T>> modules, String pId) {
       List<Tree<T>> trees = new ArrayList<>();
       for (Tree<T> treeNode : modules) {
           if (pId.equals(treeNode.getParentId())) {
               trees.add(findChildren(treeNode, modules));
           }
       }

       return trees;
   }

   /**
    *        
    *
    * @param treeNodes
    * @return
    */
   public static <T> Tree<T> findChildren(Tree<T> treeNode, List<Tree<T>> nodes) {
       for (Tree<T> it : nodes) {
           if (treeNode.getId().equals(it.getParentId())) {
               if (treeNode.getChildren() == null) {
                   treeNode.setChildren(new ArrayList<>());
               }
               treeNode.getChildren().add(findChildren(it, nodes));
           }
       }
       return treeNode;
   }
}

よびだし
public List<Tree<NoticeType>> getTree() {
        List<Tree<NoticeType>> trees = new ArrayList<>();
        List<NoticeType> list = noticeTypeMapper.selectAll();
        buildTrees(trees,list);
        return TreeUtil.buildByRecursive(trees,"0");
    }

    private void buildTrees(List<Tree<NoticeType>> trees,List<NoticeType> noticeTypes){
        noticeTypes.forEach(noticeTypes -> {
            Tree<NoticeType> tree = new Tree<>();
            tree.setId(noticeTypes.getId().toString());
            tree.setParentId(noticeTypes.getParentId().toString());
            tree.setText(noticeTypes.getName());
            trees.add(tree);
        });
    }