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}
Rohan Dodeja
  • 296
  • 1
  • 5
  • 18
  • see: http://stackoverflow.com/questions/29242665/java-how-to-adress-a-hashtable-in-a-hashtable/29242857#29242857 – midor Jul 15 '16 at 10:10
  • 3
    You are calling ```put```, which returns the previous element at that key. Since the map was empty, that is ```null```. – Jorn Vernee Jul 15 '16 at 10:16

2 Answers2

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

kohane15
  • 809
  • 12
  • 16
Alok Ray
  • 88
  • 6
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");
Bhavin Matreja
  • 88
  • 1
  • 10