All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.common.utils.TreeUtil Maven / Gradle / Ivy

There is a newer version: 2.1.11
Show newest version
package matrix.boot.common.utils;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 树结构数据工具类
 * @author wangcheng
 */
public class TreeUtil {

    /**
     * 列表转换为树
     * @param list 列表
     * @param comparator 对比类
     * @param  数据类型
     */
    public static > void toTree(List list, Comparator comparator) {
        for (T t1 : list) {
            for (T t2 : list) {
                if (t1 == t2) {
                    continue;
                }
                if (comparator.isParentWithChild(t2, t1)) {
                    if (t2.getChildren() == null) {
                        t2.setChildren(new ArrayList<>());
                    }
                    t2.getChildren().add(t1);
                    break;
                }
            }
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            if (!comparator.isTop(list.get(i))) {
                list.remove(i);
            }
        }
    }

    /**
     * 对比类
     * @param  实体
     */
    public interface Comparator {
        /**
         * 比较是否是父子
         * @param parent 参数
         * @param child 参数
         * @return boolean
         */
        boolean isParentWithChild(T parent, T child);

        /**
         * 是否是顶级
         * @param t 参数
         * @return boolean
         */
        boolean isTop(T t);
    }

    /**
     * 树对象
     * @param  实体
     */
    public static class Tree implements Serializable {

		private static final long serialVersionUID = 1L;

		private List children;

        public List getChildren() {
            return children;
        }

        public void setChildren(List children) {
            this.children = children;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy