3

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}
2
  • see: stackoverflow.com/questions/29242665/… Commented Jul 15, 2016 at 10:10
  • 3
    You are calling put, which returns the previous element at that key. Since the map was empty, that is null. Commented Jul 15, 2016 at 10:16

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

so if there are 10 nested hashmaps then i have to create 10 local hashmaps
how to extract the data of UPSSecurity
How to get 10 nested hashmap data
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.