Java Maps: take key from value

Asked

Viewed 1,646 times

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 wonder what is the most "elegant" way to get the key from the value, ie as if I pass myMap.get("valor1") and the method returns me "1", as if it were the get existing in "opposite direction". Before implementing something, I would like to know if there is already something ready in this direction.

Thank you,

  • Values will not repeat themselves?

  • can assume not, or can return the first one that gives match

3 answers

4


First, this line does not compile :

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

You cannot create an instance of an interface. In your case, it would be better to use an Hashmap since the order does not matter :

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

Also, from Java 7, you can use the operator diamond which allows you to reduce redundant code when using the germs :

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

In terms of your question, from Java 8, you can use the Stream API to fulfill 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 :

  • Recovers the Map.Entry of your map.
  • Filter flow to keep only inputs whose value is valor1.
  • Retrieves first corresponding entry.
  • Receives the value of the key.
  • If no entry is found, it returns null.

If the code is to be used several 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);
}

4

There is no official method 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;
}

Calling for:

getKeyByValue(myMap,"valor1") // 1

Functional example: https://ideone.com/Wrw2gf

This method returns the first key you find, in the link below there is the version that returns the list with the keys.

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

0

You can also double the size of your table by placing all the valores of chaves as 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");

That way just run myMap.get("valor1") to take the key of the value "valor1". See on Ideone.

Meanwhile, 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 nay could apply this technique:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.