Maps in Java: picking key from the value

4

Hello,

I have a string map for string:

Map<String,String> myMap = new Map<String,String>();

with a series of values

myMap.put("1","valor1");
myMap.put("2","valor2");
myMap.put("3","valor3");

I would like to know what is the most "elegant" way to get the key from the value, that is, as if I passed myMap.get("valor1") and the method returned me "1", like get already existing in the opposite direction. Before I implement something, I would like to know if something is already ready.

Thanks,

    
asked by anonymous 31.03.2016 / 22:20

3 answers

4

First, this line does not compile:

Map<String,String> myMap = new Map<String,String>();

You can not create an instance of an interface. In your case, it would be best to use a HashMap since the order it does not matter:

Map<String, String> myMap = new HashMap<String, String>();

In addition, from Java 7, you can use the diamond operator that allows you to reduce redundant code when using generics:

Map<String, String> myMap = new HashMap<>();

In terms of your Java 8 question, you can use Stream API to fill your need:

String key = myMap.entrySet()
                .stream()                       
                .filter(e -> e.getValue().equals("valor1"))
                .findFirst()
                .map(Map.Entry::getKey)
                .orElse(null);

Here's what we do here:

  • Retrieves the Map.Entry from your map.
  • Filter the stream to keep only entries whose value is valor1 .
  • Retrieves the first matching entry.
  • Get the value of the key.
  • If no entry is found, it returns null .

If the code is to be used multiple times, it may well be encapsulated in a method:

private String getKeyByValue(final Map<String, String> map, final String value) {
    return map.entrySet()
            .stream()
            .filter(e -> e.getValue().equals(value))
            .findFirst()
            .map(Map.Entry::getKey)
            .orElse(null);
}
    
03.04.2016 / 18:29
4

There is no official way to retrieve the key from the value, but you can implement:

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {

    for (Entry<T, E> entry : map.entrySet()) {

        if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }

    return null;
}

Call:

getKeyByValue(myMap,"valor1") // 1

Functional example: link

This method returns the first key it finds, the link below is the version that returns the list with the keys.

Source: Java Hashmap: How to get key from value?

    
31.03.2016 / 22:31
0

You can also double the size of your table by setting all valores of chaves to chaves of valores :

myMap.put("1", "valor1");
myMap.put("2", "valor2");
myMap.put("3", "valor3");

myMap.put("valor1", "1");
myMap.put("valor2", "2");
myMap.put("valor3", "3");

In this way, just run myMap.get("valor1") to get the key of the "valor1" value. See Ideone .

Mean , this will only work for tables that map only 1 value to only 1 key. And also only for tables that do not have normal values as keys. This table could not apply this technique:

myMap.put("1", "valor1");
myMap.put("2", "valor2");
myMap.put("3", "valor3");
myMap.put("valor3", "noventa");
    
31.03.2016 / 23:01