【问题标题】:How to modify key in hashmap (Java)? [closed]如何修改哈希映射(Java)中的键? [关闭]
【发布时间】:2020-11-17 07:27:49
【问题描述】:

我想更改哈希图中的键。我正在从另一个哈希图制作哈希图。

我基本上是得到一个 id 并返回一个名字。

所以基本上我得到的是:

'BOS': 300 

但我想得到:

'Boston':300
private Map<MetricName, Map<String, Integer>> getMetric(String regionId, Map<String, String> locationMap){
        Map<MetricName, Map<String, Integer>> metricTargetsMap = analyzeMetaService
                .getMetricTargetsForRegion(regionId);
        Map<MetricName, Map<String, Integer>> metricTargetsMapModified = new HashMap<MetricName, Map<String, Integer>>();
        metricTargetsMap.forEach((metricName,targetMap)-> {
                    HashMap<String, Integer> modifiedMap = new HashMap<String, Integer>();
                    targetMap.forEach((location, targetValue) -> modifiedMap.put(locationMap.get(location), targetValue));
            metricTargetsMapModified.put(metricName, modifiedMap);
                }
        );
 return metricTargetsMapModified;
}

【问题讨论】:

  • “分配数据类型”是什么意思?
  • 你会喜欢从 Java 10 开始的var
  • 请添加样本输入数据和对应的预期输出
  • INT 中的数据类型
  • 为什么您需要修改哈希映射中的键?通常认为bad practice 使用可变键,因为它可能会产生不良的副作用。如果您的意思是renaming 键,则应删除旧键并将值与新键放在一起。

标签: java hashmap key-value


【解决方案1】:

这可以通过重新映射现有地图中的键并重新收集新地图来实现:

private Map<MetricName, Map<String, Integer>> getMetric(String regionId, Map<String, String> locationMap) {
    Map<MetricName, Map<String, Integer>> metricTargetsMap = analyzeMetaService.getMetricTargetsForRegion(regionId);
    
    return metricTargetsMap
            .entrySet()
            .stream()   // stream of Map.Entry<MetricName, Map<String, Integer>>
            .map(top -> Map.entry(
                    top.getKey(),  // MetricName
                    top.getValue().entrySet()
                                  .stream()  // stream for inner map Map.Entry<String, Integer>
                                  .collect(Collectors.toMap(
                                      e -> locationMap.get(e.getKey()), // remapped key
                                      e -> e.getValue(),  // existing value
                                      (v1, v2) -> v1)  // merge function to resolve possible conflicts
                                  )
            ))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,  // MetricName
                    Map.Entry::getValue // updated map <String, Integer>
            ));
}

【讨论】:

    【解决方案2】:

    不要更改密钥。您 (a) 使用旧密钥移除项目,并且 (b) 将项目插入新密钥下。

    或者,如果你正在制作一张新地图,基本上是

      entry = oldMap.get(oldKey);
      newKey = ….whatever...;
      newMap.put(newKey, entry);
    

    在幕后,键上的某些功能被用作在地图中定位条目的机制。因此,如果您能够更改密钥,“某些功能”将不再将您带到应该找到条目的位置。

    【讨论】:

      猜你喜欢
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2018-04-14
      • 2014-10-06
      • 2018-10-13
      • 2013-12-11
      相关资源
      最近更新 更多