From c66321f3d3d215bbbcacab3945c6643efffdf022 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Sat, 24 Apr 2021 15:48:54 +0200 Subject: [PATCH] Improve BiMap API --- Core/.project | 2 +- .../fr/pandacube/lib/core/util/BiMap.java | 57 +++++++++++++++++-- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/Core/.project b/Core/.project index ddefb7a..1567b39 100644 --- a/Core/.project +++ b/Core/.project @@ -1,6 +1,6 @@ - PandacubeUtil + pandalib-core diff --git a/Core/src/main/java/fr/pandacube/lib/core/util/BiMap.java b/Core/src/main/java/fr/pandacube/lib/core/util/BiMap.java index 6109d3a..13245be 100644 --- a/Core/src/main/java/fr/pandacube/lib/core/util/BiMap.java +++ b/Core/src/main/java/fr/pandacube/lib/core/util/BiMap.java @@ -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 implements Iterable> { - HashMap map = new HashMap<>(); - HashMap inversedMap = new HashMap<>(); + protected Map map; + protected Map inversedMap; + + private BiMap reversedView = null; + + @SuppressWarnings("unchecked") + public BiMap(Supplier> mapSupplier) { + map = (Map) mapSupplier.get(); + inversedMap = (Map) mapSupplier.get(); + } + + public BiMap() { + this(HashMap::new); + } + + public BiMap(Map source) { + this(); + putAll(source); + } + + /* + * Only used for #reversedView() + */ + private BiMap(BiMap 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 source) { + for (Map.Entry 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 implements Iterable> { return Collections.unmodifiableSet(inversedMap.keySet()); } + public Map asMap() { + return Collections.unmodifiableMap(map); + } + + public BiMap reversedView() { + if (reversedView == null) + reversedView = new BiMap<>(this); + return reversedView; + } + public synchronized void forEach(BiConsumer c) { for(Entry entry : this) { c.accept(entry.getKey(), entry.getValue()); @@ -76,5 +120,6 @@ public class BiMap implements Iterable> { map.clear(); inversedMap.clear(); } + }