繁体   English   中英

如何在另一个 Map Java 中迭代 Map

[英]How to iterate through a Map inside another Map Java

我有一个包含以下数据的 map,我想处理键bookAttr中的数据

{
  "form46": {
    "bookId": 46,
    "bookAttr": {
      "title": "To Kill a Mockingbird",
      "author": "Harper Lee"
    }
  },
  "form47": {
    "bookId": 66,
    "bookAttr": {
      "title": "1984",
      "author": "George Orwell"
    }
  }
}

I tried to iterate on the initial map, however I am getting an error when trying to process the values that I have since Java is complaining that Object cannot be converted to HashMap

HashMap<String, Object> bookForm; // contains bookFormData
for (Object value : bookForm.values()) {
    HashMap<String,Object> bookAttributes = value.get("bookAttr");
    System.out.println(bookAttributes);
    //iterate over bookAttributes and do something else
}

如何遍历bookAttr以处理其内容?


bookForm的内容:

bookForm.entrySet().stream().forEach(e
                -> System.out.println(e.getKey() + "=" + e.getValue())
        );

Output:

form46={bookAttr={title=To Kill a Mockingbird, author=Harper Lee}, bookId=46}
form47={bookId=66, bookAttr={title=1984, author=George Orwell}}

似乎问题在于您正在尝试将Object值设置为HashMap类型的变量。 并且,还尝试使用Map代替HashMap

尝试更换

HashMap<String,Object> bookAttributes = value.get("bookAttr");

Map<String,Object> bookAttributes = (Map<String, Object>)value.get("bookAttr");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM