简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM