问题描述
我需要检查,如果地图包含任何从列表中的键,并且如果它再回到第一个匹配的值。浮现在脑海的幼稚的做法是做两个嵌套循环:
I need to check if map contains any of the keys from a list, and if it does then return the first matching value. The naive approach that comes to mind is to do it in two nested loops:
Map<String, String> fields = new HashMap<String, String>();
fields.put("a", "value a");
fields.put("z", "value z");
String[] candidates = "a|b|c|d".split("|");
for (String key : fields.keySet()){
for (String candidate : candidates) {
if (key.equals(candidate)){
return fields.get(key);
}
}
}
有一个更好和更有效的方式,可能的一个依赖于Java标准库?
Is there a nicer and more efficient way, possibly one relying on the Java standard library?
推荐答案
当然是这样的:
for (String candidate : candidates) {
String result = fields.get(key);
if (result != null) {
return result;
}
}
以上仅执行的有一个的地图每候选键查找。它避免了presence加上提取单独的测试,因为提取不存在的关键只会给你一个空。注(感谢的 Slanec 的),对于一个有效的密钥空值是一个不存在的键这个解决方案没有区别。
The above only performs one map lookup per candidate key. It avoids the separate test for presence plus extraction, since extracting a non-existant key will simply give you a null. Note (thanks Slanec) that a null value for a valid key is indistinguishable from a non-existant key for this solution.
我不明白你为什么要进行大小写转换,顺便说一句。
I don't quite understand why you're performing the case conversion, btw.
这篇关于快捷的方式找到,如果地图包含任意键从列表/迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!