我必须将基于属性文件映射的HashMap密钥替换为旧的-新的密钥映射。以下方法是替换密钥的最佳方法吗?
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());
}
}
}
答案 0 :(得分:4)
您本质上是在做什么:
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));
或者您也可以这样做:
Map<String, Object> result = new LinkedHashMap<>();
newKeys.asIterator()
.forEachRemaining(e -> mapToReplaceKeys.forEach((k, v) -> {
if(k.equals(e)) result.put(properties.getString(k), v);
}));
答案 1 :(得分:1)
不要在Map
上进行迭代,只是为了检查密钥是否相等。这就是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);
}
由于要删除映射,因此可以仅在remove
上使用Map
,这将不执行任何操作,并且在不存在密钥时仅返回null
。