AKJ88 AKJ88 - 1 year ago 134
Java Question

Java stream Convert list of maps to set

I have a data structure in the form of list of maps:

List< Map<String, List<String>> >

I want to collect all the elements of lists (values of maps) in a single
using java 8 features.


Input: [ {"a" : ["b", "c", "d"], "b" : ["a", "b"]}, {"c" : ["a", "f"]} ]
Output: ["a", "b", "c", "d", "f"]


Answer Source

You can use a series of Stream.map and Stream.flatMap:

List<Map<String, List<String>>> input = ...;

Set<String> output = input.stream()    // -> Stream<Map<String, List<String>>>
    .map(Map::values)                  // -> Stream<List<List<String>>>
    .flatMap(Collection::stream)       // -> Stream<List<String>>
    .flatMap(Collection::stream)       // -> Stream<String>
    .collect(Collectors.toSet())       // -> Set<String>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download