Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 820
AKJ88 Avatar asked Aug 30 '16 05:08

AKJ88


1 Answers

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>
    ;
like image 110
lazy dog Avatar answered Oct 19 '22 11:10

lazy dog