有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合如何在java中制作嵌套HashMap

我正在尝试将匿名hashmap放入另一个hashmap:-

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

输出为:-

{UPSSecurity=null}

共 (2) 个答案

  1. # 1 楼答案

    你也可以这样做

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

    请使用此方法定义嵌套哈希映射

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

    输出:

    {UPSSecurity={username=rohan}}