[英]Replace HashMap keys with values in Property file in Java
我必須基於具有舊 - 新鍵映射的屬性文件映射替換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());
}
}
}
你基本上做的是:
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);
}));
不要迭代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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.