简体   繁体   English

一个映射包含Java中的另一个Map

[英]A map contains another Map in Java

I want to create a Map which is contains another map.If there is no special key in inner Map, I want to create that key with value= 1, otherwise increment its value. 我想创建一个包含另一个地图的Map。如果内部Map中没有特殊键,我想创建value = 1的键,否则增加其值。
I wrote this code : 我写了这段代码

Map <String, Map <String,Double>> ingMap= new HashMap<>();
Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
ingMap.put("A", k);
k.put("Class2", 1.0);
ingMap.put("A", k);
k.put("Class1", 1.0);
ingMap.put("B", k);
k.put("Class2", 1.0);
ingMap.put("B", k);
k = ingMap.get("A");
if (k.containsKey("Class3")) {            
    k.put("Class3", k.get(k)+1);
    ingMap.put("A", k );
}
else{                        
    k.put("Class3", 1.0);
    ingMap.put("A",k );                       
 }
 System.out.println("\n" + ingMap); 

The result is: 结果是:

{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0, **Class3=1.0}**}

But really I wanted : 但是我真的想要:

{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0}}

You are putting the same inner map k in all the values of the outer map. 您要将相同的内部映射k放在外部映射的所有值中。 You need to create a new inner map instance for each outer map key : 您需要为每个外部地图键创建一个新的内部地图实例:

Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("A", k);

k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("B", k);

And there's no need to put the same value with the same key twice, as it does nothing. 无需将相同的值和相同的键两次放置,因为它什么也不做。

And the code for updating the inner map should be like this : 并且用于更新内部地图的代码应如下所示:

k = ingMap.get("A");
if (k != null) {
    if (k.containsKey("Class3")) {            
        k.put("Class3", k.get("Class3")+1);
    }
    else {                        
        k.put("Class3", 1.0);                    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM