嵌套的Hashmaps覆盖其他键

时间:2015-06-18 06:15:08

标签: java hashmap nested

我有一个问题,当我想在嵌套的HashMap中更改一个值时,其他的HashMaps被覆盖。

例如,我有一个密钥名称Alligator,它存储一个包含密钥Weight和Size的HashMap。我希望能够更改与Size关联的值,但不会影响Weight。在yml文件中,这就是它的样子。

Alligator:
  Weight: 100.0
  Size: 10.0

这就是我想要发生的事情。

Alligator:
  Weight: 150.0
  Size: 10.0

这是我之前发现的一些代码,它允许我更改值,但覆盖...

HashMap< String, HashMap< String, Double>> data = new HashMap<>();

       data.put("Alligator", new HashMap() {
            {
                put("Size", 10.0
            }
        });

HashMap< String, HashMap< String, Double>> data = new HashMap<>();

       data.put("Alligator", new HashMap() {
            {
                put("Weight", 100.0
            }
        });

4 个答案:

答案 0 :(得分:2)

   data.put("Alligator", new HashMap() {
        {
            put("Weight", 100.0);
        }
    });
如果“Alligator”键已经在外部Map中,

将覆盖它的内部Map。

您必须先检查是否存在:

Map<String, Double> inner = data.get("Alligator");
if (inner != null) {
    inner.put("Weight", 100.0);
} else {
    data.put ("Alligator", new HashMap() {
        {
            put("Weight", 100.0);
        }
    });
}

BTW,我不会为内部Map使用HashMap实例的匿名子类。 您可以使用这个更简单的代码替换它:

Map<String, Double> inner = data.get("Alligator");
if (inner == null) {
    inner = new HashMap<>();     
    data.put ("Alligator",inner);
}
inner.put("Weight", 100.0);

答案 1 :(得分:1)

A

new HashMap(){ // blablabla

表示memery中的新Object实例

data.put("Alligator", new HashMap() { // blablabla

表示在数据图中添加(密钥不存在)或覆盖(密钥存在)KV对。

正如@Eran建议的那样,

inner = data.get("Alligator")

检查内部是否存在

答案 2 :(得分:1)

如果您的数据HashMap中没有“Alligator”,可能会首先处理您想要发生的事情,可能会为“Alligator”添加新的HashMap

if (!data.containsKey("Alligator")) {
  data.put("Alligator", new HashMap<>());
}

然后使用get抓取嵌套的HashMap并使用put更改值:

HashMap<String, Double> alligator = data.get("Alligator");
alligator.put("Weight", 150.0);

答案 3 :(得分:0)

创建一个内部名称不同的HashMap,这样您就不会在两个地图之间感到困惑。

Map<String,Map<String,Integer>> outermap = new HashMap<String,Map<String,Integer>>();
        Map<String,Integer> innermap1 = new HashMap<String,Integer>();


        innermap1.put("Weight",100);
        innermap1.put("Size", 10);
        outermap.put("Alligator",innermap1);