Reputation: 315
I am currently saving a JSON response in a map and I'm struggling iterating over the nested HashMap values. For example:
Index 1 -> Key: "Example":
Values "Example 3" (ArrayList)
My map looks like:
HashMap<Object, Object> map = (HashMap< Object, Object >) result.getBody();
Which is saving the result from the following Spring Boot ResponseEntity:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> result = restTemplate.exchange(url, HttpMethod.GET,
entity, Object.class);
And to iterate over the first set of indexes I am doing:
for (Map.Entry<Opportunities, Opportunities> entry : resultMap.entrySet()) {
System.out.println(entry.getValue());
}
How can I iterate over the values inside Index 1? I have tried adapting this solution but with no luck. Thanks in advance.
Edit - The JSON response looks like:
{
"metadata": {
"page": 0,
"pageSize": 1,
"pageCount": 10,
"totalCount": 10
},
"Users": [
{
"ID": 1216411,
"name": "John",
"name": "John",
"Order_Details": {
"id": 1216411234,
"item": "Electric Razer",
"region": {
"name": "United States",
"regionCode": "US"
}
},
"Suppliers": [
...
Upvotes: 0
Views: 1078
Reputation: 40034
So assuming you have something like this.
Map<String,LinkedHashMap<String,Long>> map =...
for (Map<String,Long> lhms : map.values()) {
for (long value : lhms.values()) {
System.out.println(value);
}
}
Upvotes: 1
Reputation: 121649
WJS gave a very good response for the question you asked ... ... but it definitely sounds like you might want to revisit your "design".
Specifically, how do you want to map your JSON data to Java objects?
As Pshemo said, HashMaps are great for fast lookup of a given key ... but you can't easily iterate over the list in the same order you created it.
There's also the question of how "simple" or "complex" you want to make your "nested data".
All of which will affect how easy it is to create, read and/or update your list.
Strong suggestion: consider using Jackson:
https://www.baeldung.com/jackson-object-mapper-tutorial
Upvotes: 0