Rohan Dodeja
Rohan Dodeja

Reputation: 306

how to make nested HashMap in java

i'm trying to put an anonymous hashmap into another hashmap:-

Map<String, Object> requestBody=new HashMap<String, Object>();
requestBody.put("UPSSecurity", new HashMap<String, Object>().put("username","rohan"));
System.out.println(requestBody);

Output is:-

{UPSSecurity=null}

Upvotes: 3

Views: 8683

Answers (2)

Alok Ray
Alok Ray

Reputation: 88

Please use this way to define your Nested Hashmap.

Map<String, Object> requestBody=new HashMap<String, Object>();
Map<String,Object> userdetails=new HashMap<String, Object>();
userdetails.put("username","rohan");
requestBody.put("UPSSecurity",userdetails );
System.out.println(requestBody);

Output:

{UPSSecurity={username=rohan}}

Upvotes: 5

Bhavin Matreja
Bhavin Matreja

Reputation: 88

You can also do it this way.

Map<String, Object> requestBody=new HashMap<String, Object>();
requestBody.put("UPSSecurity", new HashMap<String, Object>());
requestBody.get("UPSSecurity").put("username","rohan");

Upvotes: 1

Related Questions