collections - How to group elements of a List by elements of another in Java 8 -


i have following problem: given these classes,

class person {     private string zip;     ...     public string getzip(){         return zip;     } }  class region {     private list<string> zipcodes;     ...     public list<string> getzipcodes() {         return zipcodes;     } } 

using java 8 stream api, how obtain map<person, list<region>> based on whether region contains person's zip code? in other words how group regions people zip codes belong regions?

i've done in java 7 old fashioned way, have migrate code take advantage of new features in java 8.

thank you,

impeto

i suspect cleanest way -- i'm not quite happy other answers posted -- be

 persons.stream().collect(collectors.tomap(     person -> person,     person -> regions.stream()        .filter(region -> region.getzipcodes().contains(person.getzip()))        .collect(collectors.tolist()))); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -