[英]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.