|
| 1 | +package com.jnape.palatable.lambda.functions.builtin.fn2; |
| 2 | + |
| 3 | +import com.jnape.palatable.lambda.functions.Fn1; |
| 4 | +import com.jnape.palatable.lambda.functions.Fn2; |
| 5 | + |
| 6 | +import java.util.Map; |
| 7 | +import java.util.function.Supplier; |
| 8 | + |
| 9 | +/** |
| 10 | + * Given a {@link Supplier} of some {@link Map} <code>M</code>, create an instance of <code>M</code> and put |
| 11 | + * all of the entries in the provided <code>Iterable</code> into the instance. Note that instances of <code>M</code> |
| 12 | + * must support {@link Map#put} (which is to say, must not throw on invocation). |
| 13 | + * |
| 14 | + * @param <K> the key element type |
| 15 | + * @param <V> the value element type |
| 16 | + * @param <M> the resulting map type |
| 17 | + */ |
| 18 | +public final class ToMap<K, V, M extends Map<K, V>> implements Fn2<Supplier<M>, Iterable<Map.Entry<K, V>>, M> { |
| 19 | + |
| 20 | + private static final ToMap INSTANCE = new ToMap<>(); |
| 21 | + |
| 22 | + private ToMap() { |
| 23 | + } |
| 24 | + |
| 25 | + @Override |
| 26 | + public M apply(Supplier<M> mSupplier, Iterable<Map.Entry<K, V>> entries) { |
| 27 | + M m = mSupplier.get(); |
| 28 | + entries.forEach(kv -> m.put(kv.getKey(), kv.getValue())); |
| 29 | + return m; |
| 30 | + } |
| 31 | + |
| 32 | + @SuppressWarnings("unchecked") |
| 33 | + public static <K, V, M extends Map<K, V>> ToMap<K, V, M> toMap() { |
| 34 | + return INSTANCE; |
| 35 | + } |
| 36 | + |
| 37 | + public static <K, V, M extends Map<K, V>> Fn1<Iterable<Map.Entry<K, V>>, M> toMap(Supplier<M> mSupplier) { |
| 38 | + return ToMap.<K, V, M>toMap().apply(mSupplier); |
| 39 | + } |
| 40 | + |
| 41 | + public static <K, V, M extends Map<K, V>> M toMap(Supplier<M> mSupplier, Iterable<Map.Entry<K, V>> entries) { |
| 42 | + return toMap(mSupplier).apply(entries); |
| 43 | + } |
| 44 | +} |
0 commit comments