我必须将基于属性文件映射的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());
}
}
}发布于 2018-11-22 08:36:03
你实际上是这样做的:
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);
}));发布于 2018-11-22 21:10:11
不要在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);
}因为您希望删除映射,所以可以只在Map上使用remove,它不会做任何事情,只会在键不存在时返回null。
https://stackoverflow.com/questions/53421961
复制相似问题