Search code examples
javajava-8java-streammultiset

Java Stream: combine elements in a map


I have a Map<String, List<class1> > dict and here is what I hope to do

Multiset<class1> dict1 = HashMutlset.create();
SetMultimap<class1, String> dict2 = HashMultimap.create();
for (Entry<String, List<class1>> entry : dict.entrySet()) {
   dict1.addAll(entry.getValue());
   for (class1 elem : entry.getValue()) {
       dict2.put(elem, entry.getKey());
   }
}

I hope to put all class1 object in the lists in a Multiset and also have a reverse look up of class1 object and its key.

Is there any way to write the equivalent code using stream?


Solution

  • ImmutableSetMultimap<class1, String> dict2 = dict.entrySet().stream()
       .collect(ImmutableSetMultimap.flatteningToImmutableSetMultimap(
          entry -> entry.getKey(),
          entry -> entry.getValue().stream()))
       .inverse();
    ImmutableMultiset<class1> dict1 = dict2.keys();
    

    In general, using Stream.forEach to put things into a collection is an antipattern.