Search code examples
javadictionarynestedhashmap

How to insert in a nested hashmap?


I have a nested hashmap like

HashMap<String,HashMap<String,Obzect>> map1= new HashMap<>();

The first map key will be object.getId and key of second map can be "p1","p2" or such based on some conditions. I am trying to insert into a hashmap without creating an instance for second map.

map1.put(object.getId,map1.get(object.getId).put("p1",object));

I am getting error message

Required Type: hashmap
Provided Type: object

How to correct this?


Solution

  • Try this.

    public static void main(String[] args) {
        record Obzect(String getId) {}
        Obzect object = new Obzect("id");
    
        HashMap<String, HashMap<String, Obzect>> map1= new HashMap<>();
        map1.computeIfAbsent(object.getId, k -> new HashMap<>()).put("p1", object);
    
        System.out.println(map1);
    }
    

    output:

    {id={p1=Obzect[getId=id]}}