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);
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值