beanutils转换工具类(持续更新)

218 阅读1分钟

/**
 * bean转换工具
 *
 * @author hope 2022年03月03日 下午15:27:41
 */
public class Converter extends BeanUtils {

    /**
     * toMap
     */
    public static <T, R> Map<R, T> toMap(List<T> source, Function<T, R> targetProperties) {
        return source.stream().collect(Collectors.toMap(targetProperties, v -> v, (o1, o2) -> o1));
    }

    public static <T, R> Map<R, T> toMap(List<T> source, Function<T, R> targetProperties, BinaryOperator<T> merge) {
        return source.stream().collect(Collectors.toMap(targetProperties, v -> v, merge));
    }

   /**
    * bean to beanVO
    */
    public static <T, R> R copy(T source, Supplier<R> target) {
        R r = target.get();
        copyProperties(source, r);
        return r;
    }
    
    public static <T, R> R copy(T source, Supplier<R> target, CopyListCallBack<T, R> callBack) {
        R r = target.get();
        copyProperties(source, r);
        if (Objects.nonNull(callBack)) {
            // 回调
            callBack.callBack(source, r);
        }
        return r;
    }

   /**
    * beanList to beanVOList
    */
    public static <T, R> List<R> copyList(List<T> sources, Supplier<R> target) {
        return copyList(sources, target, null);
    }

    public static <T, R> List<R> copyList(List<T> sources, Supplier<R> target, CopyListCallBack<T, R> callBack) {
        return copyList(sources, target, callBack, Boolean.TRUE);
    }

    public static <T, R> List<R> copyList(List<T> sources, Supplier<R> target, CopyListCallBack<T, R> callBack, Boolean flag) {
        return sources.stream().map(source -> {
            R r = target.get();
            if (flag) {
                copyProperties(source, r);
                if (Objects.nonNull(callBack)) {
                    // 回调
                    callBack.callBack(source, r);
                }
            } else {
                if (Objects.nonNull(callBack)) {
                    // 回调
                    callBack.callBack(source, r);
                }
                copyProperties(source, r);
            }
            return r;
        }).collect(Collectors.toList());
    }

    @FunctionalInterface
    public interface CopyListCallBack<T, R> {

        void callBack(T t, R r);

    }

}

image.png


  • [ 萱二AXW ]