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 Set using java 8 features.
Example:
Input:  [ {"a" : ["b", "c", "d"], "b" : ["a", "b"]}, {"c" : ["a", "f"]} ]
Output: ["a", "b", "c", "d", "f"]
Thanks.
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>
    ;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With