/
MultiMap.java
76 lines (61 loc) · 1.76 KB
/
MultiMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package mezz.jei.collect;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMultimap;
public class MultiMap<K, V, T extends Collection<V>> {
protected final Map<K, T> map;
private final Function<K, T> collectionMappingFunction;
public MultiMap(Supplier<T> collectionSupplier) {
this(new HashMap<>(), collectionSupplier);
}
public MultiMap(Map<K, T> map, Supplier<T> collectionSupplier) {
this.map = map;
this.collectionMappingFunction = (k -> collectionSupplier.get());
}
public T get(K key) {
return map.computeIfAbsent(key, collectionMappingFunction);
}
public boolean put(K key, V value) {
return get(key).add(value);
}
public boolean remove(K key, V value) {
T collection = map.get(key);
return collection != null && collection.remove(value);
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public boolean contains(K key, V value) {
T collection = map.get(key);
return collection != null && collection.contains(value);
}
public Set<Map.Entry<K, T>> entrySet() {
return map.entrySet();
}
public Set<K> keySet() {
return map.keySet();
}
public Collection<V> allValues() {
return this.map.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
public void clear() {
map.clear();
}
public ImmutableMultimap<K, V> toImmutable() {
ImmutableMultimap.Builder<K, V> builder = ImmutableMultimap.builder();
for (Map.Entry<K, T> entry : map.entrySet()) {
K key = entry.getKey();
for (V value : entry.getValue()) {
builder.put(key, value);
}
}
return builder.build();
}
}