Efficient way to find if map contains any of the keys from a list/iterable
Surely something like:
for (String candidate : candidates) {
String result = fields.get(key);
if (result != null) {
return result;
}
}
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.
for(String candidate : candidates) {
if(fields.containsKey(candidate)) {
return fields.get(candidate)
}
}
the best way if null values are possibly in map, and if only the first detected key is required.