Skip to content

Instantly share code, notes, and snippets.

@adamw
Created January 16, 2018 12:14
Show Gist options
  • Save adamw/78a3a73c3ac9a63a25f9f3191103f9b4 to your computer and use it in GitHub Desktop.
Save adamw/78a3a73c3ac9a63a25f9f3191103f9b4 to your computer and use it in GitHub Desktop.
<K, V> void addToMultimap(ConcurrentHashMap<K, Set<V>> map, K key, V value) {
map.compute(key, (k, v) -> {
if (v == null) {
v = ConcurrentHashMap.newKeySet();
}
v.add(value);
return v;
});
}
<K, V> void removeFromMultimap(ConcurrentHashMap<K, Set<V>> map, K key, V value) {
map.computeIfPresent(key, (k, v) -> {
v.remove(value);
if (v.size() == 0) {
return null;
} else {
return v;
}
});
}
@viktorklang
Copy link

Yeah, something like this:

    <K, V> void addToMultimap(ConcurrentHashMap<K, Set<V>> map, K key, V value) {
        map.compute(key, (k, v) -> {
            if (v == null) {
                v = ConcurrentHashMap.newKeySet();
            }
            v.add(value);
            return v;
        });
    }

    <K, V> void removeFromMultimap(ConcurrentHashMap<K, Set<V>> map, K key, V value) {
        map.computeIfPresent(key, (k, v) -> {
            return (v.remove(value) && !v.isEmpty) ? v : null;
        });
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment