Create and Invert MultiMap w/ Java 8 Streams -


how can convert set<result> map<item, set<string>> or setmultimap<item, string> using java 8 streams or multimaps, result is:

class result {     string name;     set<item> items; } 

for example, start with:

result1:     name: name1     items:         - item1         - item2 result2:     name: name2     items:         - item2         - item3 

and end with:

item1:     - name1 item2:     - name1     - name2 item3:     - name2 

two important methods in code snippet below stream.flatmap & collectors.mapping:

import java.util.map.entry; import java.util.abstractmap.simpleentry; import static java.util.stream.collectors.*;  results.stream()     //map stream<result> stream<entry<item>,string>    .flatmap(it -> it.items.stream().map(item -> new simpleentry<>(item, it.name)))    //group result.name item     .collect(groupingby(entry::getkey, mapping(entry::getvalue, toset()))); 

Comments