【问题标题】:Replace HashMap keys with values in Property file in Java用 Java 中的属性文件中的值替换 HashMap 键
【发布时间】:2018-11-21 23:38:53
【问题描述】:

我必须将基于属性文件映射的 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());            
    }
  }
}

【问题讨论】:

    标签: java java-8 hashmap


    【解决方案1】:

    你实际上在做的是:

    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,找到一个相等的键……感觉太……错了……
    【解决方案2】:

    不要遍历 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

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2023-03-18
      • 2012-05-09
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多