|
@@ -0,0 +1,78 @@
|
|
|
+package com.simuwang.base.utils;
|
|
|
+
|
|
|
+import cn.hutool.core.collection.ListUtil;
|
|
|
+
|
|
|
+import java.io.Serializable;
|
|
|
+import java.util.Comparator;
|
|
|
+import java.util.List;
|
|
|
+import java.util.function.BiConsumer;
|
|
|
+import java.util.function.Function;
|
|
|
+
|
|
|
+public class TreeUtil {
|
|
|
+ // list转树,不排序
|
|
|
+ public static <T> List<T> list2Tree(List<T> list,
|
|
|
+ Function<T, Serializable> getId,
|
|
|
+ Function<T, Serializable> getParentId,
|
|
|
+ Function<T, List<T>> getChildren,
|
|
|
+ BiConsumer<T, List<T>> setChildren,
|
|
|
+ Object root) {
|
|
|
+ return list2Tree(list, getId, getParentId, getChildren, setChildren, root, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ // list转树,可排序
|
|
|
+ public static <T> List<T> list2Tree(List<T> list,
|
|
|
+ Function<T, Serializable> getId,
|
|
|
+ Function<T, Serializable> getParentId,
|
|
|
+ Function<T, List<T>> getChildren,
|
|
|
+ BiConsumer<T, List<T>> setChildren,
|
|
|
+ Object root,
|
|
|
+ Function<T, Comparable> getOrder) {
|
|
|
+ List<T> treeList = ListUtil.list(false);
|
|
|
+ for (T tree : list) {
|
|
|
+ //check root
|
|
|
+ if (objEquals(root, getParentId.apply(tree))) {
|
|
|
+ treeList.add(tree);
|
|
|
+ }
|
|
|
+ //find tree's Children
|
|
|
+ for (T treeNode : list) {
|
|
|
+ if (objEquals(getId.apply(tree), getParentId.apply(treeNode))) {
|
|
|
+ if (getChildren.apply(tree) == null) {
|
|
|
+ setChildren.accept(tree, ListUtil.list(false));
|
|
|
+ }
|
|
|
+ getChildren.apply(tree).add(treeNode);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (getOrder != null) {
|
|
|
+ List<T> childList = getChildren.apply(tree);
|
|
|
+ if (childList != null && childList.size() > 1) {
|
|
|
+ List<T> sortList = getSortList(childList, getOrder);
|
|
|
+ setChildren.accept(tree, sortList);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return treeList;
|
|
|
+ }
|
|
|
+
|
|
|
+ //对比对象是否相等
|
|
|
+ public static boolean objEquals(Object a, Object b) {
|
|
|
+ if (a == null)
|
|
|
+ return b == null;
|
|
|
+ return a.equals(b);
|
|
|
+ }
|
|
|
+
|
|
|
+ //list排序
|
|
|
+ public static <T> List<T> getSortList(List<T> list, Function<T, Comparable> getOrder) {
|
|
|
+ List<T> sortList = ListUtil.list(false);
|
|
|
+ List<T> nullOrderList = ListUtil.list(false);
|
|
|
+ for (T item : list) {
|
|
|
+ if (null == getOrder.apply(item)) {
|
|
|
+ nullOrderList.add(item);
|
|
|
+ } else {
|
|
|
+ sortList.add(item);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ sortList.sort(Comparator.comparing(getOrder::apply));
|
|
|
+ sortList.addAll(nullOrderList);
|
|
|
+ return sortList;
|
|
|
+ }
|
|
|
+}
|