简体   繁体   中英

Nested map to list of string

I have a map with this structure

Map<String, Object> data

    "data": {
       "contacts": [
        "20228",
        "20118"
        ],
  "phone": "555555"
}

I would like to know how can I get a list from this data map, something like:

List<String> expectedOutput = ["368188", "20118", "555555"]

I tried with this

var list = data.values().stream().collect(Collectors.toList());

But I am getting a List with the nested list of contacts and this not what I am expecting to have.

Map<String, Object> map = new HashMap<>();
map.put("a", List.of("a1", "a2"));
map.put("b", "b1");

List<String> list =
    (List<String>)
        map
            .values()                        // Collection<Object>
            .stream()                        // Stream<Object>
            .flatMap(
                o -> {
                  if (o instanceof List) {
                    return ((List) o).stream();
                  } else {
                    return Stream.of(o);
                  }
                })                           // Stream<Object>
            .collect(Collectors.toList());   // Object

System.out.println(list);                    // [a1, a2, b1]

You have a weird situation here. You have a Stream of objects which can have Stream s or primitive types -- which is not a good design, imo.

The goal can still be achieved with .flatMap() . You'll need to cast the .collect() because the Stream interface relies on generic typing, and you erased all it's benefits by starting a Stream<Object> so the return type of your stream pipeline is Object when its source is a raw type.


One liner for .flatMap() :

.flatMap(o -> o instanceof List ? ((List) o).stream() : Stream.of(o))

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