Building on Alexander Ivanchenko's answer, you could get the first non-null value from the map based on a series of alternate keys:
public static Optional<String> getValue(Map<String, String> map,
String keyA, String... keys) {
Optional<String> result = Optional.ofNullable(map.get(keyA));
for (String key : keys) {
if (result.isPresent()) break;
result = result.or(() -> Optional.ofNullable(map.get(key)));
}
return result;
}
You could use the getOrDefault
method of map, but something like
map.getOrDefault("keyA", map.getOrDefault("keyB", map.get("keyC")))
seems overly specific and complicated, and you still have to deal with the fact that neither keyA nor keyB nor keyC might be present, so you might still get null
, and this has the performance penalty of looking up all three values from the map no matter which is returned.
It also only works for three keys.