简体   繁体   English

如何根据值获取地图的钥匙

[英]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 . 这是我的程序,有人可以告诉我如何根据该值获取Map的密钥。

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

    }

}

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
    }
}

You can do manual iteration, or use one of Apache Common Collections Libraries . 您可以进行手动迭代,也可以使用Apache Common Collections库之一
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). Interface BidiMap <K,V>是双向映射,允许您将键映射到值,也可以将值映射到键 (使用getKey();方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM