2

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);

    }

}
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • 1
    related: http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – FourScore Jan 09 '15 at 14:13
  • 2
    Mapping is one way, so you have iterate through all the keys to get the one you need (and we have assumed that K-V pairs are 1:1). – meskobalazs Jan 09 '15 at 14:13
  • 4
    What if there are two different keys with the same value? Which key would you want to have? –  Jan 09 '15 at 14:13
  • instead of getting highest value first and then retrieve the vendor, iterate on map keep a tab on the highest price and its vendor.At the end of loop you will get your highest vendor. Ofcourse since more than one vendor can have same price, so save vendors having highest price in a list. – Sikorski Jan 09 '15 at 14:38

2 Answers2

3

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
    }
}
Mena
  • 47,782
  • 11
  • 87
  • 106
1

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).

Ali Lotfi
  • 856
  • 3
  • 18
  • 40