AKJ88 AKJ88 - 3 months ago 13
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
Set
using java 8 features.

Example:

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


Thanks.

Answer

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>
    ;
Comments