如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?
当前回答
/**
* This method gets the Key for the given Value
* @param paramName
* @return
*/
private String getKeyForValueFromMap(String paramName) {
String keyForValue = null;
if(paramName!=null)) {
Set<Entry<String,String>> entrySet = myMap().entrySet();
if(entrySet!=null && entrySet.size>0) {
for(Entry<String,String> entry : entrySet) {
if(entry!=null && paramName.equalsIgnoreCase(entry.getValue())) {
keyForValue = entry.getKey();
}
}
}
}
return keyForValue;
}
其他回答
是的,您必须遍历hashmap,除非您按照这些不同答案所建议的方式实现某些东西。而不是摆弄entrySet,我只获得keySet(),遍历该集合,并保留为您提供匹配值的(第一个)键。如果你需要所有匹配这个值的键,显然你需要做所有的事情。
正如Jonas所建议的,这可能已经是containsValue方法正在做的事情,所以您可以完全跳过这个测试,而只是每次都进行迭代(或者编译器可能已经消除了冗余,谁知道呢)。
另外,相对于其他答案,如果你的反向映射看起来像
Map<Value, Set<Key>>
如果需要这种功能,您可以处理非唯一key->值映射(先解开它们)。这将把fine纳入人们建议的任何解决方案中,使用两张地图。
public class NewClass1 {
public static void main(String[] args) {
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Entry<Integer, String> entry : testMap.entrySet()) {
if (entry.getValue().equals("c")) {
System.out.println(entry.getKey());
}
}
}
}
一些额外的信息…可能对你有用
如果你的hashmap真的很大,上面的方法可能不太好。如果您的hashmap包含唯一键到唯一值的映射,您可以维护一个包含从值到键映射的hashmap。
也就是说你必须维护两个hashmap
1. Key to value
2. Value to key
在这种情况下,您可以使用第二个hashmap来获取key。
设值为maxValue。
Set keySet = map.keySet();
keySet.stream().filter(x->map.get(x)==maxValue).forEach(x-> System.out.println(x));
没有明确的答案,因为多个键可以映射到相同的值。如果要在自己的代码中强制执行唯一性,最好的解决方案是创建一个类,该类使用两个hashmap在两个方向上跟踪映射。
要找到映射到该值的所有键,请使用map. entryset()遍历hashmap中的所有对。
推荐文章
- 将枚举转换为集合/列表
- 在Java中创建对象数组
- Java中字符串的字节数
- IntelliJ IDEA with Junit 4.7”!!JUnit 3.8或更高版本:
- 既然JavaScript和Java没有任何关系,它为什么被称为JavaScript ?
- 番石榴vs Apache Commons
- Java是编译型编程语言还是解释型编程语言?
- 我如何通过Java应用程序使用GMail,雅虎或Hotmail发送电子邮件?
- 注释@GetMapping和@RequestMapping(method = RequestMethod.GET)之间的区别
- lambda表达式中使用的变量应该是final或有效final
- 如何创建数组列表的数组?
- noclassdeffounderror:无法初始化类XXX
- 如何创建今天午夜和明天午夜的Java日期对象?
- ByteBuffer在Java中的用途是什么?
- 使Hibernate忽略未映射的实例变量