Java树工具类,mysql树工具类

Java树工具类,mysql树工具类依赖<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.6.0</version></dependency><dependency><groupI

大家好,又见面了,我是你们的朋友全栈君。

package com.ciih.workshop.utils;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.SneakyThrows;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 树形工具类-函数版
 *
 * @author sunziwen
 */

public class TreeUtil {


    /**
     * Map版本(速度比递归要快很多)
     * listToTree
     *
     * @param target      需转换的数据
     * @param getId       主键
     * @param getParentId 父id (父id必须和主键相同类型)
     * @param getChildren 子集
     * @param setChildren 子集
     * @return tree
     */
    public static <T, R> List<T> listToTree(List<T> target, Function<T, R> getId, Function<T, R> getParentId,
                                            Function<T, List<T>> getChildren, BiConsumer<T, List<T>> setChildren) {

        Map<R, T> oldMap = target.stream().collect(Collectors.toMap(getId, T -> T));
        List<T> result = new ArrayList<>();
        target.forEach(tree -> {
            T parent = oldMap.get(getParentId.apply(tree));
            if (parent == null) {
                result.add(tree);
            } else {
                List<T> ch = getChildren.apply(parent);
                if (ch == null) {
                    ch = new ArrayList<>();
                }
                ch.add(tree);
                setChildren.accept(parent, ch);
            }
        });
        return result;
    }

    /**
     * @param list          树结构的基础数据集
     * @param getIdFn       获取主键的函数
     * @param getParentIdFn 获取父节点的函数
     * @param getChildrenFn 获取子集的函数
     * @param <T>           t
     * @param <R>           r
     * @return t
     */
    @SneakyThrows
    public static <T, R> List<T> treeOut(List<T> list, Function<T, R> getIdFn, Function<T, R> getParentIdFn, SFunction<T, R> getChildrenFn) {
        /*所有元素的Id*/
        List<Object> ids = list.stream().map(getIdFn).collect(Collectors.toList());
        /*查出所有顶级节点*/
        List<T> topLevel = list.stream().filter(x -> {
            R apply = getParentIdFn.apply(x);
            return !ids.contains(apply);
        }).collect(Collectors.toList());
        return TreeUtil.recursion(topLevel, list, getIdFn, getParentIdFn, getChildrenFn);
    }


    @SneakyThrows
    private static <T, R> List<T> recursion(List<T> superLevel, List<T> list, Function<T, R> getIdFn, Function<T, R> getParentIdFn, SFunction<T, R> getChildrenFn) {
        //获取setChildren的Method
        Method writeReplaceMethod = getChildrenFn.getClass().getDeclaredMethod("writeReplace");
        boolean accessible = writeReplaceMethod.isAccessible();
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(getChildrenFn);
        writeReplaceMethod.setAccessible(accessible);
        String setMethodName = serializedLambda.getImplMethodName().replaceFirst("g", "s");
        Method setMethod = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredMethod(setMethodName, List.class);

        for (T t : superLevel) {
            List<T> children = list.stream().filter(x -> {
                R apply = getParentIdFn.apply(x);
                R apply1 = getIdFn.apply(t);
                return apply.equals(apply1);
            }).collect(Collectors.toList());
            if (children.size() <= 0) {
                continue;
            }

            List<T> recursion = recursion(children, list, getIdFn, getParentIdFn, getChildrenFn);
            setMethod.invoke(t, recursion);
        }
        return superLevel;
    }


}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/148050.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • arping指令linux,arping

    arping指令linux,arping例a,指定IP发送ARP请求[root@Blackghost~]arping192.168.1.11ARPING192.168.1.11from192.168.1.6eth0Unicastreplyfrom192.168.1.11[08:00:27:7e:b8:08]2.780msUnicastreplyfrom192.168.1.11[08:00:27:7e:b8…

    2022年6月10日
    44
  • cobol语言基础教程_boo语言

    cobol语言基础教程_boo语言一、基础知识1.程序结构division-部section-节paragraphs-段2.四个部(1)IDENTIFICATIONDIVISION程序的标识部,位于程序的顶部,主要定义了程序的Id,作者等信息。(2)ENVIRONMENTDIVISION环境部声明了程序运行的环境,指定了程序的输入和输出文件,有两个节组成,配置节和输入输出节①配置节由两个段组成,分别是指定了程序编译的环境节(源计算机)和运行环境(目标计算机)②输入输出节由两个段组成分别是文

    2025年7月6日
    2
  • css height 100% 和 100vh 区别

    css height 100% 和 100vh 区别1.height100%意思就是,想在这container设置高度![有约束]高度设置成100%但是呢这得看container的父级body的height是否为100%还往上看body的父级html的height是否为100%container->body->html[他们的height元素都要设置为100%]<html><head><style>html,bod

    2022年5月18日
    61
  • db2 中sql 拼接字符串

    db2 中sql 拼接字符串最近在使用db2中时,一段sql需要拼接字符串,不能直接使用 +例如:like‘%’+#{paramter}+‘%’ mysql可以,但是db2中应使用如下:like‘%’||#{patamter}||‘%’;特此记录。以便记住…

    2022年6月15日
    80
  • 大数据应用及其解决方案(完整版)

    大数据应用及其解决方案(完整版)目录1、大数据概述1.1.概述1.2.大数据定义1.3.大数据技术发展2、大数据应用2.1.大数据应用阐述2.2.大数据应用架构2.3.大数据行业应用2.3.1.医疗行业2.3.2.能源行业2.3.3.通信行业2.3.4.零售业3、大数据解决方案3.1.大数据技术组成3.1.1.分析技术3.1.2.存储数据库…

    2022年6月2日
    52
  • MySql修改表名的两种方法

    MySql修改表名的两种方法一、renamerenametable旧表名to新表名;renametablemysutonew_su;二、alteraltertable旧表名rename[as]新表名altertablemysurenameasnew_su;

    2022年6月1日
    2.2K

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号