Skip to content

Instantly share code, notes, and snippets.

@gtrak
Created November 24, 2014 22:34
Show Gist options
  • Save gtrak/89e88a961f6318088c68 to your computer and use it in GitHub Desktop.
Save gtrak/89e88a961f6318088c68 to your computer and use it in GitHub Desktop.
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