简体   繁体   English

有什么方法可以从 HashMap 中获取包含 HashMaps 的 ArrayList 的值列表?

[英]Is there any way to get list of values from HashMap contains of ArrayList of HashMaps?

I want to get a List of Data Transfer Objects from the response i got from the third party API.我想从我从第三方 API 得到的响应中获取数据传输对象列表。 The structure of the third party API's response is as follows:第三方API的响应结构如下:

Map<String,Object>
{
    {
        String -> ArrayList{
                        <Key,Value(DTO)>,
                        <Key,Value(DTO)>,
                        <Key,Value(DTO)>,
                        ...
                    }
    },

    {
        String -> Hashmap
    }
}

Response Type: Map(String,Object)响应类型: Map(String,Object)

I got two key-value pairs.我有两个键值对。 1(String,ArrayList ( HashMap(s)... ) ) , 2(String,HashMap) 1(String,ArrayList (HashMap(s)...)), 2(String,HashMap)

Now I want the list of the values of all the HashMaps of ArrayList .现在我想要ArrayList的所有HashMap的值列表。

I want the List as :我希望列表为:

List<DTO>{
    {
        "key":"value",
        "key":"value"
    },
    {
        "key":"value",
        "key":"value",
        "key":"value",
        "key":"value"
    }
}

sample response from api:来自api的示例响应:

{ "one": [ 0 : { "id":"435453ty5g8437t5g734tr", "name":"name1", "address":"add", "field":"new field" }, 1: { "id":"4fr74g8fg48346rt83486tf", "name":"name2", "address":"add1", "field":"new field22" } ], 
 "meta": { "current_page":1, "records_per_page":20, "total_records":null } }

how i need :我如何需要:

[ { "id":"435453ty5g8437t5g734tr", "name":"name1", "address":"add", "field":"new field" }, 
  { "id":"4fr74g8fg48346rt83486tf", "name":"name2", "address":"add1", "field":"new field22" } ] 

You may :你可以 :

  1. filter the entries where the values is a List过滤值为List的条目
  2. Map from Object to List<Map<String, DTO>>Object映射到List<Map<String, DTO>>
  3. flatMap to put all maps together in the same stream flatMap将所有地图放在同一个流中
  4. Collect all收集所有

This is the unchecked version, for the generic type of the List这是未经检查的版本,用于List的泛型类型

List<Map<String, DTO>> result =
         content.values().stream()
                         .filter(value -> value instanceof List)
                         .map(value -> (List<Map<String, DTO>>) value)
                         .flatMap(List::stream)
                         .collect(Collectors.toList());

System.out.println(result);

> Online Demo

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

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