-1

I want to change the key in a hashmap. I am making a hashmap from another hashmap.

I am basically getting an id and returning a name.

So basically what I am getting is:

'BOS': 300 

But I want to get:

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

2 Answers2

0

This can be implemented by re-mapping keys in the existing map and re-collecting new map:

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>
            ));
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

You don't change the key. You (a) remove the item using the old key, and (b) insert the item under the new key.

Alternatively, if as in your case you are making a new map, it's basically

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

Under the covers, some function on the key is used as the mechanism to locate the entry in the map. So if you were able to change the key, the "some function" would no longer take you to the place where the entry should have been found.

user14644949
  • 321
  • 1
  • 3