简体   繁体   English

用Java中的Property文件中的值替换Ha​​shMap键

[英]Replace HashMap keys with values in Property file in Java

I have to replace HashMap keys based on a property file mapping with old - new key mapping. 我必须基于具有旧 - 新键映射的属性文件映射替换HashMap键。 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());            
    }
  }
}

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);
       }));

Don't iterate over a Map , just to check the keys for equality. 不要迭代Map ,只是检查键是否相等。 That's what the Map 's dedicated lookup methods are for: 这就是Map的专用查找方法的用途:

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. 由于您要删除映射,因此您只需在Map上使用remove ,它将不执行任何操作,只在键不存在时返回null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM