java - Transforming Map<Key, List<Value>> to Map<Key, Value> -


what have:

    sortedset<person> ss = new treeset<>();      ss.add(new person("john", "doe", 20));     ss.add(new person("max", "power", 26));     ss.add(new person("bort", "bort", 30));     ss.add(new person("scorpio", "mcgreat", 56));      map<integer, list<person>> list = ss.stream().collect(collectors.groupingby(p -> p.name.length())); 

i need transform map map<integer, person> know need use flatmap purpose don't know how.

what have tried far: value-set , flatmap it.

map <integer, person> list2 = list.values()                                     .stream()                                     .flatmap(f -> f.stream())                                     .collect(collectors.groupingby(f -> f.name.length()); //doesn't work 

question: far understand java returns values lists when create maps via streams, how can flatmap lists ?

additional info: implementation of compareto

@override public int compareto(person o) {      int cmp = this.surname.compareto(o.surname);     if(cmp == 0){         cmp = this.name.compareto(o.name);     }      return cmp; } 

disclaimer:

i know use-case little bit odd since sort according length , use compareto comparing length of name. imho doesn't matter question since map<key, list<value>>. question is: how map<key,value>

in fact requirement not make sense. want group property, implies it's not bijective function. type of values of resulting map list default. if know function apply bijective, can supply downstream collector / or use tomap collector, having throwing merger parameter (the best option imo).

so example:

map<integer, person> list =      ss.stream()       .collect(collectors.tomap(p -> p.surname.length(),                                  p -> p,                                  (p1, p2) -> {throw new illegalstateexception("duplicate key length " + p1.surname.length());})); 

outputs in case:

{3=(john, doe, 20), 4=(bort, bort, 30), 5=(max, power, 26), 7=(scorpio, mcgreat, 56)} 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -