简体   繁体   中英

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. The structure of the third party API's response is as follows:

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

    {
        String -> Hashmap
    }
}

Response Type: Map(String,Object)

I got two key-value pairs. 1(String,ArrayList ( HashMap(s)... ) ) , 2(String,HashMap)

Now I want the list of the values of all the HashMaps of ArrayList .

I want the List as :

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

sample response from 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
  2. Map from Object to List<Map<String, DTO>>
  3. flatMap to put all maps together in the same stream
  4. Collect all

This is the unchecked version, for the generic type of the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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