|
| 1 | +package in.kuros.jfirebase.util; |
| 2 | + |
| 3 | +import com.google.common.collect.Sets; |
| 4 | +import lombok.AccessLevel; |
| 5 | +import lombok.NoArgsConstructor; |
| 6 | +import lombok.RequiredArgsConstructor; |
| 7 | + |
| 8 | +import java.util.HashMap; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Set; |
| 11 | +import java.util.function.BiConsumer; |
| 12 | +import java.util.function.BinaryOperator; |
| 13 | +import java.util.function.Function; |
| 14 | +import java.util.function.Supplier; |
| 15 | +import java.util.stream.Collector; |
| 16 | + |
| 17 | +@NoArgsConstructor(access = AccessLevel.PRIVATE) |
| 18 | +public final class CustomCollectors { |
| 19 | + |
| 20 | + public static <T, K, V> Collector<T, Map<K, V>, Map<K, V>> toMap(final Function<? super T, K> keyMapper, |
| 21 | + final Function<T, V> valueMapper) { |
| 22 | + return new CustomCollectorImpl<>(HashMap::new, |
| 23 | + (kvMap, t) -> kvMap.put(keyMapper.apply(t), valueMapper.apply(t)), |
| 24 | + (kvMap, kvMap2) -> { |
| 25 | + kvMap.putAll(kvMap2); |
| 26 | + return kvMap; |
| 27 | + }, |
| 28 | + Function.identity(), |
| 29 | + Collector.Characteristics.IDENTITY_FINISH); |
| 30 | + } |
| 31 | + |
| 32 | + public static <T, K, V> Collector<T, Map<K, V>, Map<K, V>> toMap(final Function<? super T, K> keyMapper, |
| 33 | + final Function<T, V> valueMapper, |
| 34 | + final BinaryOperator<V> mergeFunction) { |
| 35 | + return new CustomCollectorImpl<>(HashMap::new, |
| 36 | + (kvMap, t) -> { |
| 37 | + final K key = keyMapper.apply(t); |
| 38 | + kvMap.put(key, mergeFunction.apply(kvMap.get(key), valueMapper.apply(t))); |
| 39 | + }, |
| 40 | + (kvMap, kvMap2) -> { |
| 41 | + kvMap.putAll(kvMap2); |
| 42 | + return kvMap; |
| 43 | + }, |
| 44 | + Function.identity(), |
| 45 | + Collector.Characteristics.IDENTITY_FINISH); |
| 46 | + } |
| 47 | + |
| 48 | + @RequiredArgsConstructor |
| 49 | + static class CustomCollectorImpl<T, A, R> implements Collector<T, A, R> { |
| 50 | + |
| 51 | + private final Supplier<A> supplier; |
| 52 | + private final BiConsumer<A, T> accumulator; |
| 53 | + private final BinaryOperator<A> combiner; |
| 54 | + private final Function<A, R> finisher; |
| 55 | + private final Characteristics characteristics; |
| 56 | + |
| 57 | + @Override |
| 58 | + public Supplier<A> supplier() { |
| 59 | + return supplier; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public BiConsumer<A, T> accumulator() { |
| 64 | + return accumulator; |
| 65 | + } |
| 66 | + |
| 67 | + @Override |
| 68 | + public BinaryOperator<A> combiner() { |
| 69 | + return combiner; |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public Function<A, R> finisher() { |
| 74 | + return finisher; |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public Set<Characteristics> characteristics() { |
| 79 | + return Sets.newHashSet(characteristics); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments