Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define hashmap within hashmap using object of other hashmap

Tags:

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

if i have call Title1 that time they call another hashmap. i want this type of output

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

first hashmap object call second hashmap key

like image 343
Bhoomi Loriya Avatar asked Nov 27 '25 06:11

Bhoomi Loriya


1 Answers

If I correct undestand what you want, use following code

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"

OR you can create new class

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

and just use HashMap < HashKey, String > hm, for example:

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

  ...
  String s = hm.get(new HashKey("Title1", "Key 1")); // Value
like image 60
Slava Vedenin Avatar answered Nov 28 '25 20:11

Slava Vedenin