Java: one of many keymaps

I have a card that may contain one of the following keys

Map<String, String> map = getMap(); 

Now I want to check if one of some keys is installed. My current approach is to chain several map.getOrDefault(...)

 Address address = new Address(); address.setStreet(map.getOrDefault("STORE_STREET" , map.getOrDefault("OFFICE_STREET", ...)); 

or check each key if it exists on 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 card is given as such.

+6
source share
2 answers

Normally, getOrDefault is a way, but if you have several alternative keys, this not only affects readability, but also turns the performance advantage back. With type code:

 address.setStreet(map.getOrDefault("STORE_STREET", map.getOrDefault("OFFICE_STREET", ...)); 

you first look at alternative keys to get the recession value before you even see if a primary key (or a key with a higher priority) is present.

The decision will be

 Stream.of("STORE_STREET", "OFFICE_STREET", ...) .map(map::get) .filter(Objects::nonNull) .findFirst() .ifPresent(address::setStreet); 

When doing this at a time, its performance may be less than a simple cycle, however, due to the higher initialization costs, the difference in performance will then be irrelevant. For frequent execution there will be no significant difference, so you have to decide based on readability (which, of course, is subjective).

+11
source
 String []keys = {"STORE_STREET", "OFFICE_STREET", ...}; for (String k : keys) { if (map.containsKey(k)) return map.get(k); } return ""; // or throw an exception 
+1
source

Source: https://habr.com/ru/post/1014377/


All Articles