java - Stuck with java8 lambda expression -


i have map<integer,doctor> doclib=new hashmap<>(); save class of doctor.

class doctor has methods:getspecialization() return string,
getpatients() return collection of class person.

in main method, type:

public map<string,set<person>> getpatientsperspecialization(){     map<string,set<person>> res=this.doclib.entryset().stream().                          map(d->d.getvalue()).                          collect(groupingby(d->d.getspecialization(),                                             d.getpatients()) //error                                  );    return res; } 

as can see, have problem groupingby,i try send same value d method, it's wrong. how solve this?

you need second collector mapping :

public map<string,set<person>> getpatientsperspecialization(){     return this.doclib                .values()                .stream()                .collect(colectors.groupingby(doctor::getspecialization,                                              collectors.mapping(doctor::getpatients,toset()))                        ); } 

edit:

i think original answer may wrong (it's hard without being able test it). since doctor::getpatients returns collection, think code may return map<string,set<collection<person>>> instead of desired map<string,set<person>>.

the easiest way overcome iterate on map again produce desired map :

public map<string,set<person>> getpatientsperspecialization(){     return this.doclib                .values()                .stream()                .collect(colectors.groupingby(doctor::getspecialization,                                              collectors.mapping(doctor::getpatients,toset()))                        )                .entryset()                .stream()                .collect (collectors.tomap (e -> e.getkey(),                                            e -> e.getvalue().stream().flatmap(c -> c.stream()).collect(collectors.toset()))                         ); } 

perhaps there's way same result single stream pipeline, can't see right now.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -