java - 如何根据值获取Map的key

标签 java

这是我的程序,有人可以告诉我如何根据值获取 map 的 key 。

我已经尝试过

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

但它让我返回 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);

    }

}

最佳答案

没有反向映射。

您可以做的是迭代条目并将这些值与您想要的值进行比较,如果相等则获取键。

当然,多个键可以具有相同的值!

例如:

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

关于java - 如何根据值获取Map的key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862443/

相关文章:

java android 获取类

java - 带有动态文本的正则表达式

java - 如何从 Amazon elastic map reduce 中的映射器访问文件内容?

java - ReSTLet如何解码HTTP基本认证中的secret

javascript - 如何禁用 Tapestry T 控制台?

java - 有序流处理元素的状态映射操作是否以确定性方式进行?

java - 在 TreeMap 中键入返回 null

java - VisualVM OQL : find object that has (indirect) reachables/references to two object IDs?

java - Java 中对两个字节变量求和的异常

java - 如何修改附加到多个 JButton 的操作监听器的参数?