Skip to content

Commit bb15b6e

Browse files
committed
adding ToMap, used to create maps from iterables of entries
1 parent a88e4cd commit bb15b6e

File tree

2 files changed

+69
-0
lines changed
  • src
    • main/java/com/jnape/palatable/lambda/functions/builtin/fn2
    • test/java/com/jnape/palatable/lambda/functions/builtin/fn2

2 files changed

+69
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.jnape.palatable.lambda.functions.builtin.fn2;
2+
3+
import org.junit.Test;
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
9+
import static com.jnape.palatable.lambda.functions.builtin.fn2.ToMap.toMap;
10+
import static java.util.Arrays.asList;
11+
import static org.junit.Assert.assertEquals;
12+
13+
public class ToMapTest {
14+
15+
@Test
16+
public void collectsEntriesIntoMap() {
17+
Map<String, Integer> expected = new HashMap<String, Integer>() {{
18+
put("foo", 1);
19+
put("bar", 2);
20+
put("baz", 3);
21+
}};
22+
23+
assertEquals(expected, toMap().apply(HashMap::new, asList(tuple("foo", 1), tuple("bar", 2), tuple("baz", 3))));
24+
}
25+
}

0 commit comments

Comments
 (0)