davioooh
davioooh

Reputation: 24706

Double keyset Map

I need a Map<String,Integer> to store a binding between a set o strings and ints, for example:

"one"   <-> 1
"two"   <-> 2
"three" <-> 3

and in particular I need to use both String values and int values as key to access this map. I mean: get("one") returns 1 and get(1) returns "one".

What's the best way to achieve this? is there some Map implementation that can help me?

Upvotes: 1

Views: 119

Answers (2)

AppX
AppX

Reputation: 528

Could possible create an inverted map on demand. This wont support same value for two keys.

public class InvertableMap<K, V>  extends HashMap<K, V> {

    public  InvertableMap<V, K> getInvertedMap() {
        InvertableMap<V, K> outputMap = new InvertableMap<>();
        for (K k : keySet()) {
            V v = get(k);
            outputMap.put(v, k);
        }
        return outputMap;
    }
}

Upvotes: 0

Martin Dinov
Martin Dinov

Reputation: 8825

Either use two HashMaps and write a method to query one of the two depending on what input you are giving it (String or int) or use the Guava library's HashBiMap, which does something like that behind the scenes for you.

Upvotes: 1

Related Questions