What collection to use in Java?

I want to map integers to strings, they are one-to-one, for example:

60 : c
61 : c#
62 : d
63 : d#
64 : e
65 : f
66 : f#

But I need to be able to do the following:

  • Get the value from the key: "c" = getValue (60) [give it a key of 60, return the value of the string]
  • get the key from the value: 65 = getKey ("f") [give it the string value "f", return the key]

Which collection model is best for this? I ask, because I looked at several of them, no one can do part <2>. Or do I need to write code to go through each pair to find which key has the value "f"?

Edit: nothing in jdk1.6 does this?

+3
source share
6

( )

    public class ReversibleMap {
       private final Map keyToValue = new HashMap(8);
       private final Map valueToKey = new HashMap(8);

       public void put(Integer key, String value) {
           keyToValue.put(key, value);
           valueToKey.put(value, key);
       }

       public String get(Integer key) {
           return (String) keyToValue.get(key);
       }

       public Integer getKey(String value) {
           return (Integer) valueToKey.get(value);
      }
   }

0
+14

guava, - foreach. , ( ). , - . , .

+6

BiMap. google guava .

+5

Java : () java jdk1.6,

1) , 2 , ^^

2) , ? ArrayList?

+1

If these are musical notes with a fixed set of key-value pairs, then you can use enuma reverse lookup card. You will still get two HashMaps, but at least they are combined into an enumeration.

enum Note {
    C("C",60), CSHARP("C#",61), D("D",62), DSHARP("D#",63); //etc..
    final int value;
    final String symbol;
    static final Map<Integer, Note> lookup = new HashMap<Integer, Note>();
    static {
        for(Note n : Note.values()) {
            lookup.put(n.value, n);
        }
    }

    Note(String symbol, int value) {
        this.symbol = symbol;
        this.value = value;
    }

    static Note get(int i) {
        return lookup.get(i);
    }
}

Then, to get the values ​​and characters, use this

System.out.println(Note.get(61));
System.out.println(Note.get(61).symbol);
System.out.println(Note.CSHARP.value);
System.out.println(Note.CSHARP.symbol);

leading to

CSHARP
C#
61
C#

PS. Modifiers are removed for brevity. Pss. Add another search map for the symbol.

+1
source

Source: https://habr.com/ru/post/1771853/


All Articles