Using Java 8 lambdas/transformations to combine and flatten two Maps -


i have 2 maps:

  • map<a, collection<b>> mapab
  • map<b, collection<c>> mapbc

i transform them map<a, collection<c>> mapac , i'm wondering if there's smooth way lambdas , transformations. in particular case, collections sets, i'd solve problem collections in general.

one thought had first combine 2 maps map<a, map<b, collection<c>>> , flatten it, i'm open approach.

data notes: b should occur in value collection associated 1 a, , same true mapbc (a given c mapped 1 b). result, there should 1 path given a given c, although there may a -> b mappings there no b -> c mappings , there may b -> c mappings there no corresponding a -> b mappings. these orphans don't appear in resulting mapac.

for sake of comparison, here's example of purely imperative approach same problem:

map<a, collection<c>> mapac = new hashmap<>();  (entry<a, collection<b>> entry : mapab.entryset()) {     collection<c> cs = new hashset<>();      (b b : entry.getvalue()) {         collection<c> origcs = mapbc.get(b);         if (origcs != null) {             cs.addall(origcs);         }     }      if (!cs.isempty()) {         mapac.put(entry.getkey(), cs);     } } 

you didn't specify want if b first map don't exist in second map, may not looking for.

mapab.entryset().stream()   .filter(e -> e.getvalue().stream().anymatch(mapbc::containskey))   .collect(tomap(        map.entry::getkey,        e->e.getvalue().stream()            .filter(mapbc::containskey)            .map(mapbc::get)            .flatmap(collection::stream)            .collect(tolist())   )); 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

Kivy: Swiping (Carousel & ScreenManager) -

jdbc - Not able to establish database connection in eclipse -