这是我的程序,有人可以告诉我如何根据值获取 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/