java基础之生成树

1、以菜单为例

TreeToolUtils工具类

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.main.entity.Menu;

import java.util.*;


/**
 * 树
 */
public class TreeToolUtils {

    private List<Menu> rootList; //根节点对象存放到这里

    private List<Menu> bodyList; //其他节点存放到这里,可以包含根节点

    public TreeToolUtils() {
    }

    public TreeToolUtils(List<Menu> rootList, List<Menu> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    // 删除ArrayList中重复元素,保持顺序
    public static List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        list.clear();
        list.addAll(newList);
        System.out.println(" remove duplicate " + list);
        return list;
    }

    //调用的方法入口
    public List<Menu> getTree() {
        if (bodyList != null && !bodyList.isEmpty()) {
            //声明一个map,用来过滤已操作过的数据
            Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return rootList;
    }

    public void getChild(Menu beanTree, Map<String, String> map) {
        List<Menu> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getMenuId()))
                .filter(c -> c.getParentId().equals(beanTree.getMenuId()))
                .forEach(c -> {
                    map.put(c.getMenuId().toString(), c.getParentId().toString());
                    getChild(c, map);
                    childList.add(c);
                });
        Collections.sort(childList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                // 升序排列
                if (o1.getOrderNum() > o2.getOrderNum()) {
                    return 1;
                }
                if (o1.getOrderNum().equals(o2.getOrderNum())) {
                    return 0;
                }
                return -1;
            }
        });
        beanTree.setChildren(childList);
    }

}
发布了49 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/csdnzhang365/article/details/95353674