如何使用另一个哈希映射对象定义哈希映射内的哈希映射

3
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,那么它会调用另一个哈希表。我想要这种类型的输出。

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

第一个哈希表对象调用第二个哈希表键

3个回答

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 < HashKey, String > hm,例如:

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

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

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");

你使用了三个HashMap,但我想只使用两个HashMap。 - Bhoomi Loriya
@BhoomiLoriya 我只是使用了第三个 HashMap 来获取目的,并向您展示它。如果您告诉我您需要什么,那么我可以考虑一下,如果可能的话,我会在这里回复答案。 - Vishal Gajera

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();
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接