1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; import com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda; import com.ruben.pojo.User;
import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector;
public class FunctionUtils {
public static <T, K, U> Map<K, U> toHashMap(List<T> list, Function<T, K> keyFunction, Function<T, U> valueFunction) { if (Objects.isNull(list) || list.isEmpty()) { return new HashMap<>(0); } return list.stream().collect(MyCollectors.toHashMap(keyFunction, valueFunction)); }
public static <T, K> Map<K, T> toHashMap(List<T> list, Function<T, K> keyFunction) { return toHashMap(list, keyFunction, null); }
public static <T> Map<?, T> toHashMap(List<T> list) { return toHashMap(list, null, null); }
public static class MyCollectors {
public static <T, K, U> Collector<T, HashMap<K, U>, HashMap<K, U>> toHashMap(Function<T, K> keyFunction, Function<T, U> valueFunction) { return new MyCollectorImpl<>(HashMap::new, (m, v) -> m.put(Optional.ofNullable(keyFunction).map(keyF -> keyF.apply(v)).orElseGet(() -> { try { return (K) v.getClass().getMethod("getId").invoke(v); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return null; }), Optional.ofNullable(valueFunction).map(valueF -> valueF.apply(v)).orElse((U) v)), (u, v) -> null, i -> i, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH))); }
public static class MyCollectorImpl<T, A, R> implements Collector<T, A, R> { private final Supplier<A> supplier; private final BiConsumer<A, T> accumulator; private final BinaryOperator<A> combiner; private final Function<A, R> finisher; private final Set<Characteristics> characteristics;
MyCollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Set<Characteristics> characteristics) { this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; this.finisher = finisher; this.characteristics = characteristics; }
@Override public Supplier<A> supplier() { return supplier; }
@Override public BiConsumer<A, T> accumulator() { return accumulator; }
@Override public BinaryOperator<A> combiner() { return combiner; }
@Override public Function<A, R> finisher() { return finisher; }
@Override public Set<Characteristics> characteristics() { return characteristics; } } } }
|