如何使用其他hashmap的对象在hashmap中定义hashmap

时间:2015-12-03 13:43:08

标签: java hashmap

HashMap<String, HashMap<String, String>> hm = new HashMap<String, HashMap<String, String>>();
        hm.put("Title1","Key1");
            for(int i=0;i<2;i++) {
                HashMap<String, String> hm1 = new HashMap<String, String>();
                hm1.put("Key1","Value1");
            }

如果我在调用Title1时调用另一个hashmap。我想要    这种类型的输出

hm<key,value(object hm1)>
hm<key,value)

第一个hashmap对象调用第二个hashmap键

3 个答案:

答案 0 :(得分:1)

如果我纠正你想要的东西,请使用以下代码

HashMap<String, HashMap<String, String>> hm = new HashMap<>();
            HashMap<String, String> hm1 = new HashMap<>();
            for(int i=0;i<2;i++) {
                hm1.put("Key1","Value1");
            }
        hm.put("Title1", hm1); // save hm

...

HashMap<String, String> hm2 = hm.get("Title1"); 
String s = hm2.get("Key1"); // s =  "Value1"

或者你可以创建新的课程

class HashKey {
 private String title;
 private String key;
 ...
 // getters, setters, constructor, hashcode and equals
} 

只需使用HashMap&lt; HashKey,String&gt;嗯,例如:

  hm.put(new HashKey("Title1", "Key 1"), "Value");

  ...
  String s = hm.get(new HashKey("Title1", "Key 1")); // Value

答案 1 :(得分:1)

你可以做同样的事情,

HashMap<String,HashMap<String,String>> hm = new HashMap<String,HashMap<String,String>>();

HashMap<String,String> hm1 = new HashMap<String,String>();
hm1.put("subkey1","subvalue");

hm.put("Title1",hm1);

HashMap<String,String> newhm = hm.get("Title1");

答案 2 :(得分:1)

import java.util.HashMap;
import java.util.Map;

public class MapInMap {
    Map<String, Map<String, String>> standards =
 new HashMap<String, Map<String, String>>();

    void addValues() {
        Map<String, String> studentA = new HashMap<String, String>();
        studentA.put("A1", "49");
        studentA.put("A2", "45");
        studentA.put("A3", "43");
        studentA.put("A4", "39");
        standards.put("A", studentA);
        Map<String, String> studentB = new HashMap<String, String>();
        studentB.put("B1", "29");
        studentB.put("B2", "25");
        studentB.put("B3", "33");
        studentB.put("B4", "29");
        standards.put("B", studentB);

    }

    void disp() {
        for (Map.Entry<String, Map<String, String>> entryL1 : standards
                .entrySet()) {
            System.out.println("Standard :" + entryL1.getKey());
            for (Map.Entry<String, String> entryL2 : entryL1.getValue()
                    .entrySet()) {
                System.out.println(entryL2.getKey() + "/" + entryL2.getValue());
            }
        }

    }

    public static void main(String args[]) {
        MapInMap inMap = new MapInMap();
        inMap.addValues();
        inMap.disp();
    }

}