1

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?

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • 2
    Guava BiMap should do the job: https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap – Marco13 Jul 07 '14 at 09:53
  • Yes.. `BiMap` is the way to go – TheLostMind Jul 07 '14 at 09:53
  • http://stackoverflow.com/questions/2574685/java-how-to-use-googles-hashbimap – Vahid Jul 07 '14 at 10:01
  • @Marco13 Thank you, please write your answer so I can pick it up. – davioooh Jul 07 '14 at 10:54
  • There are hundreds of questions like this. First websearch result: http://stackoverflow.com/questions/9783020/bidirectional-map Upvote whatever you want to upvote, a link is not really an "answer" in the stackoverflow sense... – Marco13 Jul 07 '14 at 12:10

2 Answers2

1

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.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
0

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;
    }
}
AppX
  • 528
  • 2
  • 12