Skip to content

Instantly share code, notes, and snippets.

@jedws
Created August 22, 2012 04:46
Show Gist options
  • Select an option

  • Save jedws/3422342 to your computer and use it in GitHub Desktop.

Select an option

Save jedws/3422342 to your computer and use it in GitHub Desktop.
Java version of the unionWith algorithm – scala version here https://gist.github.com/3412529
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
public final class Maps {
public interface Combiner<K, A> {
A combine(K k, A a, A b);
}
public interface Semigroup<A> {
A append(A a, A b);
}
static <K, V> Semigroup<Map<K, V>> unionWithKey(final Combiner<K, V> semi) {
return new Semigroup<Map<K, V>>() {
public Map<K, V> append(Map<K, V> left, Map<K, V> right) {
Builder<K, V> builder = ImmutableMap.builder();
MapDifference<K, V> diff = Maps.difference(left, right);
builder.putAll(diff.entriesOnlyOnLeft());
builder.putAll(diff.entriesOnlyOnRight());
for (Entry<K, V> e : diff.entriesInCommon().entrySet()) {
K key = e.getKey();
V value = e.getValue();
builder.put(key, semi.combine(key, value, value));
}
for (Entry<K, ValueDifference<V>> e : diff.entriesDiffering().entrySet()) {
K key = e.getKey();
ValueDifference<V> value = e.getValue();
builder.put(key, semi.combine(key, value.leftValue(), value.rightValue()));
}
return builder.build();
}
};
}
static <K, V> Semigroup<Map<K, V>> unionWith(final Semigroup<V> semi) {
return unionWithKey(new Combiner<K, V>() {
public V combine(K k, V a, V b) {
return semi.append(a, b);
};
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment