PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to insert in a nested hashmap?

 September 20, 2022     dictionary, hashmap, java, nested     No comments   

Issue

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]}}


Answered By - 英語は苦手
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing