I got a Map, which may contain one of the following Keys
Map<String, String> map = getMap();
I now want to check if one of some Keys are set. My current approach is to chain multiple map.getOrDefault(...)
Address address = new Address();
address.setStreet(map.getOrDefault("STORE_STREET"
, map.getOrDefault("OFFICE_STREET", ...));
or check for each key if it exists in the map.
if(map.containsKey("STORE_STREET")){
address.setStreet(map.get("STORE_STREET"));
}else if(map.containsKey("OFFICE_STREET")){
address.setStreet(map.get("OFFICE_STREET"));
}
Is there any way to make this easier/better to read? Unfortunately the map is given as such.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With