Created
November 24, 2014 22:34
-
-
Save gtrak/89e88a961f6318088c68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static class Tuple2<T,U>{ | |
final T v1; | |
final U v2; | |
Tuple2(T v1, U v2){ | |
this.v1 = v1; | |
this.v2 = v2; | |
} | |
} | |
private static <K,V> void merge(Map<K,V> m, K k, V v, Function<Tuple2<V, V>,V> f){ | |
V oldValue = m.get(k); | |
V newValue = (oldValue == null) ? v : f.apply(new Tuple2<V,V>(oldValue, v)); | |
if (newValue == null) | |
m.remove(k); | |
else | |
m.put(k, newValue); | |
} | |
private static <K,V> HashMap<K, V> mergeWith(Map<K,V> m1, Map<K,V> m2, Function<Tuple2<V,V>,V> vFunction){ | |
HashMap<K, V> m3 = new HashMap<K,V>(m1); | |
for (Map.Entry<K, V> e: m2.entrySet()){ | |
merge(m3, e.getKey(), e.getValue(), vFunction); | |
} | |
return m3; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment