Pawan
Pawan

Reputation: 32321

How to get the key of a Map based on the value

This is my program , could anybody please tell me how do i get Map's key based on the value .

I have tried as

String vendor_name = map.get("value");

But its returing me null

import java.util.Collections;
import java.util.HashMap;

public class Test {

    public static void main(String args[]) {

        HashMap<String, String> for_highest_price_vendor = new HashMap<String, String>();

        for_highest_price_vendor.put("vendor1", "20");
        for_highest_price_vendor.put("vendor2", "25");
        String maxValueInMap = (Collections.max(for_highest_price_vendor
                .values())); // This will return max value in the Hashmap

        String vendor_name = for_highest_price_vendor.get(maxValueInMap);

        System.out.println(vendor_name);

    }

}

Upvotes: 2

Views: 86

Answers (2)

Ali Lotfi
Ali Lotfi

Reputation: 941

You can do manual iteration, or use one of Apache Common Collections Libraries.
Interface BidiMap <K,V> is a bi-directional map, allowing you to map a key to a value and also to map a value to a key (using getKey(); method).

Upvotes: 1

Mena
Mena

Reputation: 48404

There is no reverse mapping.

What you can do is iterate the entries and compare the values with your desired value, then get the key if it equals.

Of course, multiple keys can have an equal value!

For instance:

Map<String, String> foo = new HashMap<String, String>();
foo.put("foo", "bar");
for (Map.Entry<String, String> entry: foo.entrySet()) {
    if (entry.getValue().equals("bar")) {
        System.out.println(entry.getKey());
        break; // or not, you may want to add to a Collection and return it once the loop is completed
    }
}

Upvotes: 3

Related Questions