Improve BiMap API

This commit is contained in:
Marc Baloup 2021-04-24 15:48:54 +02:00
parent 133b9917b4
commit c66321f3d3
2 changed files with 52 additions and 7 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PandacubeUtil</name>
<name>pandalib-core</name>
<comment></comment>
<projects>
</projects>

View File

@ -3,23 +3,57 @@ package fr.pandacube.lib.core.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
public class BiMap<K, V> implements Iterable<Entry<K, V>> {
HashMap<K, V> map = new HashMap<>();
HashMap<V, K> inversedMap = new HashMap<>();
protected Map<K, V> map;
protected Map<V, K> inversedMap;
private BiMap<V, K> reversedView = null;
@SuppressWarnings("unchecked")
public BiMap(Supplier<Map<?, ?>> mapSupplier) {
map = (Map<K, V>) mapSupplier.get();
inversedMap = (Map<V, K>) mapSupplier.get();
}
public BiMap() {
this(HashMap::new);
}
public BiMap(Map<K, V> source) {
this();
putAll(source);
}
/*
* Only used for #reversedView()
*/
private BiMap(BiMap<V, K> rev) {
map = rev.inversedMap;
inversedMap = rev.map;
reversedView = rev;
}
public synchronized void put(K k, V v) {
if (map.containsKey(k) || inversedMap.containsKey(v)) {
map.remove(k);
inversedMap.remove(v);
}
if (containsKey(k))
remove(k);
if (containsValue(v))
removeValue(v);
map.put(k, v);
inversedMap.put(v, k);
}
public synchronized void putAll(Map<? extends K, ? extends V> source) {
for (Map.Entry<? extends K, ? extends V> e : source.entrySet()) {
put(e.getKey(), e.getValue());
}
}
public synchronized V get(K k) {
return map.get(k);
@ -62,6 +96,16 @@ public class BiMap<K, V> implements Iterable<Entry<K, V>> {
return Collections.unmodifiableSet(inversedMap.keySet());
}
public Map<K, V> asMap() {
return Collections.unmodifiableMap(map);
}
public BiMap<V, K> reversedView() {
if (reversedView == null)
reversedView = new BiMap<>(this);
return reversedView;
}
public synchronized void forEach(BiConsumer<K, V> c) {
for(Entry<K, V> entry : this) {
c.accept(entry.getKey(), entry.getValue());
@ -76,5 +120,6 @@ public class BiMap<K, V> implements Iterable<Entry<K, V>> {
map.clear();
inversedMap.clear();
}
}