猿问

Java是否具有带有反向查找的HashMap?

我有以“键-键”格式而不是“键-值”格式组织的数据。这就像一个HashMap,但是我将需要在两个方向上进行O(1)查找。这种数据结构有名称吗,Java的标准库中是否包含类似的名称?(或者Apache Commons?)

我可以编写自己的类,该类基本上使用两个镜像的Map,但我不想重蹈覆辙(如果已经存在,但我只是没有在寻找正确的术语)。


慕慕森
浏览 670回答 3
3回答

哆啦的时光机

Java API中没有此类。您想要的Apache Commons类将成为BidiMap的实现之一。作为数学家,我将这种结构称为双射。

慕田峪9158850

这是我用来完成此操作的简单类(我不想再有第三方依赖项)。它没有提供“地图”中的所有可用功能,但是是一个好的开始。&nbsp; &nbsp; public class BidirectionalMap<KeyType, ValueType>{&nbsp; &nbsp; &nbsp; &nbsp; private Map<KeyType, ValueType> keyToValueMap = new ConcurrentHashMap<KeyType, ValueType>();&nbsp; &nbsp; &nbsp; &nbsp; private Map<ValueType, KeyType> valueToKeyMap = new ConcurrentHashMap<ValueType, KeyType>();&nbsp; &nbsp; &nbsp; &nbsp; synchronized public void put(KeyType key, ValueType value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyToValueMap.put(key, value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueToKeyMap.put(value, key);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; synchronized public ValueType removeByKey(KeyType key){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ValueType removedValue = keyToValueMap.remove(key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueToKeyMap.remove(removedValue);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return removedValue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; synchronized public KeyType removeByValue(ValueType value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeyType removedKey = valueToKeyMap.remove(value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyToValueMap.remove(removedKey);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return removedKey;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public boolean containsKey(KeyType key){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return keyToValueMap.containsKey(key);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public boolean containsValue(ValueType value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return keyToValueMap.containsValue(value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public KeyType getKey(ValueType value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return valueToKeyMap.get(value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public ValueType get(KeyType key){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return keyToValueMap.get(key);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

慕工程0101907

这是我的2美分。或者,您可以对泛型使用简单的方法。小菜一碟。public static <K,V> Map<V, K> invertMap(Map<K, V> toInvert) {&nbsp; &nbsp; Map<V, K> result = new HashMap<V, K>();&nbsp; &nbsp; for(K k: toInvert.keySet()){&nbsp; &nbsp; &nbsp; &nbsp; result.put(toInvert.get(k), k);&nbsp; &nbsp; }&nbsp; &nbsp; return result;}当然,您必须具有唯一值的映射。否则,将替换其中之一。
随时随地看视频慕课网APP

相关分类

Java
我要回答