简体   繁体   English

如何在内部具有嵌套ArrayList的HashMap上进行迭代

[英]How to iterate over a HashMap with a nested ArrayList inside

I am currently saving a JSON response in a map and I'm struggling iterating over the nested HashMap values. 我目前正在将JSON响应保存在地图中,并且正在尝试对嵌套的HashMap值进行迭代。 For example: 例如:

  • Index 0 索引0
  • Index 1 -> Key: "Example": 索引1->键:“示例”:

    • Key: "Example 2" 关键字:“示例2”
    • Values "Example 3" (ArrayList) 值“示例3”(ArrayList)

      • Key, Values... (HashMap) 键,值...(HashMap)

My map looks like: 我的地图看起来像:

HashMap<Object, Object> map = (HashMap< Object, Object >) result.getBody();

Which is saving the result from the following Spring Boot ResponseEntity: 这将保存以下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? 如何遍历索引1中的值? I have tried adapting this solution but with no luck. 我曾尝试调整此解决方案,但没有运气。 Thanks in advance. 提前致谢。

Edit - The JSON response looks like: 编辑-JSON响应如下所示:

{
"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": [
        ...

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

WJS gave a very good response for the question you asked ... ... but it definitely sounds like you might want to revisit your "design". WJS对您提出的问题给出了很好的答复……但是,听起来确实像您可能想重新考虑您的“设计”。

Specifically, how do you want to map your JSON data to Java objects? 具体来说,您想如何将JSON数据映射到Java对象?

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. 就像Pshemo所说的那样,HashMaps非常适合快速查找给定的键……但是您不能轻易地以创建它的顺序来遍历列表。

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: 强烈建议:考虑使用Jackson:

https://www.baeldung.com/jackson-object-mapper-tutorial https://www.baeldung.com/jackson-object-mapper-tutorial

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

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