Java: one of many keys map
Normally, getOrDefault
would be the way to go, but if you have multiple alternative keys, this does not only affect readability, but also turn the performance advantage into the opposite. With code like:
address.setStreet(map.getOrDefault("STORE_STREET", map.getOrDefault("OFFICE_STREET", ...));
You are looking up the alternative keys first, to get the fall-back value, before even looking whether the primary key (or a key with a higher precedence) is present.
One solution would be
Stream.of("STORE_STREET", "OFFICE_STREET", ...)
.map(map::get)
.filter(Objects::nonNull)
.findFirst()
.ifPresent(address::setStreet);
When executing this a single time, its performance might be less than a simple loop, due to the higher initialization overhead, however, the performance difference would be irrelevant then. For frequent execution, there will be no significant difference, so you should decide based on the readability (which is subjective, of course).