gpt4 book ai didi

java - 用 Java 中的属性文件中的值替换 HashMap 键

转载 作者:搜寻专家 更新时间:2023-11-01 02:19:19 25 4
gpt4 key购买 nike

我必须将基于属性文件映射的 HashMap 键替换为新旧键映射。以下方法是替换 key 的最佳方法吗?

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

关于java - 用 Java 中的属性文件中的值替换 HashMap 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53421961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com