G Josh
G Josh

Reputation: 311

How to iterate through a Map inside another Map Java

I have a map that contains data below, and I want to process the data inside the key 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
}

How can iterate over bookAttr to be able to process its contents?


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

Upvotes: 0

Views: 156

Answers (1)

Vladimir Shefer
Vladimir Shefer

Reputation: 739

Seems like the problem is that you are trying to set the Object value to variable of HashMap type. And, also try using Map instead of HashMap.

Try to replace

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

with

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

Upvotes: 1

Related Questions