一个关系工具类 依赖hutool

882 阅读1分钟
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 关系工具类
 */
public class RelationalUtils {

    /**
     * 根据传入字段将list 转为 map list key为传入对应属性名称的value
     *
     * @param propertyName 属性名称
     * @param recordList   列表
     */
    public static <T> Map<String, List<T>> oneToMany(String propertyName, List<T> recordList) {
        Map<String, List<T>> map = new HashMap<>(16);
        if (CollectionUtil.isEmpty(recordList) || StrUtil.isBlank(propertyName)) {
            return map;
        }
        for (T record : recordList) {
            Object o = ReflectUtil.getFieldValue(record, propertyName);
            if (Objects.isNull(o)) {
                continue;
            }
            //为避免类型冲突 统一转换为String
            String id = o.toString();
            List<T> list = map.get(id);
            if (CollectionUtil.isEmpty(list)) {
                list = new ArrayList<T>();
                list.add(record);
                map.put(id, list);
            } else {
                list.add(record);
            }
        }
        return map;
    }

    /**
     * 一对一工具类 key 为传入对应的工具的值
     *
     * @param propertyName 属性名称
     * @param recordList   实体类型列表
     */
    public static <T> Map<String, T> oneToOne(String propertyName, List<T> recordList) {
        Map<String, T> map = new HashMap<>(16);
        if (CollectionUtil.isEmpty(recordList) || StrUtil.isBlank(propertyName)) {
            return map;
        }
        for (T record : recordList) {
            Object o = ReflectUtil.getFieldValue(record, propertyName);
            if (Objects.isNull(o)) {
                continue;
            }
            //为避免类型冲突 统一转换为String
            String id = o.toString();
            map.put(id, record);
        }
        return map;
    }

    @Data
    static class Father {
        private Integer id;
        private String name;
        private List<Sun> sunList;
    }

    @Data
    static class Sun {
        private Integer id;
        private String name;
        private Integer fatherId;
    }

    public static void main(String[] args) {
        Father father = new Father();
        father.setId(1);
        father.setName("父亲");

        Sun sun = new Sun();
        sun.setId(2);
        sun.setFatherId(1);
        sun.setName("儿子");
        Sun sun1 = new Sun();
        sun1.setFatherId(3);
        sun1.setFatherId(2);
        sun1.setName("不是你的儿子");
        List<Sun> sunList = Stream.of(sun, sun1).collect(Collectors.toList());
        System.out.println(sunList);
        Map<String,List<Sun>> sunMap = oneToMany("fatherId", sunList);

        List<Sun> sunList1 = sunMap.get(father.getId().toString());
        father.setSunList(sunList1);
        System.out.println(father.toString());

    }

}