4

I have to replace HashMap keys based on a property file mapping with old - new key mapping. Is the below approach best way of replacing keys?

KeyMapping.properties

newKey1 oldLKey1
newKey2 oldKey2


//Load property mapping file
ResourceBundle properties = ResourceBundle.getBundle("KeyMapping");

Enumeration<String> newKeys = properties.getKeys();
        Map<String, Object> result = new LinkedHashMap<>();

  while (newKeys.hasMoreElements()) {
    String newKey = (String) newKeys.nextElement();
    Iterator<Entry<String, Object>> iterator = mapToReplaceKeys.entrySet().iterator();

    while(iterator.hasNext()) {
       Entry<String, Object> entry = iterator.next();

      //If key matches the key in property file       
      if (entry.getKey().equals(newKey)) {

      //remove the entry from map mapToReplaceKeys
      iterator.remove();

      //add the key with the 'oldKey' and existing value
      result.put(properties.getString(newKey), entry.getValue());            
    }
  }
}
Naman
  • 27,789
  • 26
  • 218
  • 353
user679526
  • 845
  • 4
  • 16
  • 39

2 Answers2

4

What you're essentially doing is this:

Map<String, Object> result = Collections.list(properties.getKeys())
                .stream()
                .flatMap(element -> mapToReplaceKeys.entrySet()
                        .stream()
                        .filter(entry -> entry.getKey().equals(element)))
                .collect(toMap(e -> properties.getString(e.getKey()),
                        Map.Entry::getValue,
                        (l, r) -> r,
                        LinkedHashMap::new));

or you could also do:

Map<String, Object> result = new LinkedHashMap<>();
newKeys.asIterator()
       .forEachRemaining(e -> mapToReplaceKeys.forEach((k, v) -> {
             if(k.equals(e)) result.put(properties.getString(k), v);
       }));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

Don’t iterate over a Map, just to check the keys for equality. That’s what the Map’s dedicated lookup methods are for:

ResourceBundle properties = ResourceBundle.getBundle("KeyMapping");
Map<String, Object> result = new LinkedHashMap<>();

for(String newKey: properties.keySet()) {
    Object value = mapToReplaceKeys.remove(newKey);
    if(value != null) result.put(properties.getString(newKey), value);
}

Since you want to remove the mappings, you can just use remove on the Map, which will do nothing and just return null when the key is not present.

Holger
  • 285,553
  • 42
  • 434
  • 765