首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中用属性文件中的值替换HashMap键

在Java中用属性文件中的值替换HashMap键
EN

Stack Overflow用户
提问于 2018-11-22 07:38:54
回答 2查看 790关注 0票数 4

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

代码语言:javascript
复制
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());            
    }
  }
}
EN

回答 2

Stack Overflow用户

发布于 2018-11-22 08:36:03

你实际上是这样做的:

代码语言:javascript
复制
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));

或者你也可以这样做:

代码语言:javascript
复制
Map<String, Object> result = new LinkedHashMap<>();
newKeys.asIterator()
       .forEachRemaining(e -> mapToReplaceKeys.forEach((k, v) -> {
             if(k.equals(e)) result.put(properties.getString(k), v);
       }));
票数 4
EN

Stack Overflow用户

发布于 2018-11-22 21:10:11

不要在Map上迭代,只是为了检查键是否相等。这就是Map的专用查找方法的用途:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53421961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档