Java 双向映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9783020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:37:04  来源:igfitidea点击:

Bidirectional Map

javadictionary

提问by mawia

Can you suggest a kind of map or similar data structure where we can get both the value and key from each other at equal ease. That is to say, that each may be used to find other.

你能建议一种地图或类似的数据结构,我们可以同样轻松地从彼此那里获取值和键。也就是说,每个都可以用来找到另一个。

回答by Joni

The most common solution is using two maps. You can easily encapsulate them in a class with a friendly interface by extending AbstractMap. (Update:This is how Guava's HashBiMapis implemented: two maps)

最常见的解决方案是使用两个地图。您可以通过扩展AbstractMap. (更新:这是 Guava 的HashBiMap实现方式:两张地图)

Creating a new data structure using nothing but arrays and custom classes has few advantages. The map implementations are lightweight wrappers of a data structure that indexes the keys. Since you need two indexes you might as well use two complete maps.

仅使用数组和自定义类创建新的数据结构几乎没有优势。映射实现是索引键的数据结构的轻量级包装器。由于您需要两个索引,您不妨使用两个完整的地图。

回答by Jesper

Java doesn't have a bidirectional map in its standard library.

Java 在其标准库中没有双向映射。

Use for example BiMap<K, V>from Google Guava.

使用例如BiMap<K, V>来自Google Guava

回答by Buhake Sindi

Google Guavacontains a BiMap(BiDirectional Map).

Google Guava包含一个BiMap(BiDirectional Map)。

回答by kervin

Also try Apache Commons Collections 4 BidiMapPackage.

还可以尝试 Apache Commons Collections 4 BidiMap包。

回答by Javanator

If you feel it pain importing some third party library. How about this simple class.

如果你觉得导入一些第三方库很痛苦。这个简单的类怎么样。

public class BiMap<K,V> {

    HashMap<K,V> map = new HashMap<K, V>();
    HashMap<V,K> inversedMap = new HashMap<V, K>();

    void put(K k, V v) {
        map.put(k, v);
        inversedMap.put(v, k);
    }

    V get(K k) {
        return map.get(k);
    }

    K getKey(V v) {
        return inversedMap.get(v);
    }

}

Make sure K and V class has proper hashCode implementation.

确保 K 和 V 类具有正确的 hashCode 实现。

回答by Gregor

well for the average usecase where you need a Dictionary like that, I see nothing wrong with a KISS solution, just put'ting the key and value vice versa, saving the overhead of a second Map or even library only for that purpose:

对于需要这样的字典的一般用例,我认为 KISS 解决方案没有任何问题,只需将键和值放在相反的位置,仅为此目的节省第二个 Map 甚至库的开销:

myMap.put("apple", "Apfel");
myMap.put("Apfel", "apple");

回答by Narsi Reddy Nallamilli

You can define an enum and define helper method to get key. Performance is way too far better compared to BidiMap. E.g

您可以定义一个枚举并定义辅助方法来获取密钥。与 BidiMap 相比,性能要好得多。例如

public enum Fruit {
        APPLE("_apple");
        private final String value;
        Fruit(String value){
            this.value=value;
        }
        public String getValue(){
            return this.value;
        }
        public static String getKey(String value){
            Fruit fruits[] = Fruit.values();
            for(Fruit fruit : fruits){
                if(value.equals(fruit.value)){
                    return fruit.name();
                }
            }
            return null;        }
    }

回答by Davut Gürbüz

Based on this answerin this QA and its comments I wrote following. [Will be tested]

基于此 QA 中的这个答案及其评论,我写了以下内容。[将被测试]

Bidirectional Map

双向映射

import java.util.HashMap;

public class BidirectionalMap<K, V> extends HashMap<K, V> {
private static final long serialVersionUID = 1L;
public HashMap<V, K> inversedMap = new HashMap<V, K>();

public K getKey(V value) {              
    return inversedMap.get(value);
}

@Override
public int size() {
    return this.size();
}

@Override
public boolean isEmpty() {
    return this.size() > 0;
}

@Override
public V remove(Object key) {
    V val=super.remove(key);
    inversedMap.remove(val);
    return val;
}

@Override
public V get(Object key) {
    return super.get(key);
}

@Override
public V put(K key, V value) {      
    inversedMap.put(value, key);
    return super.put(key, value);
}

}