collections - Map with LIst using Collectors.toMap in Java 8 -


i convert below code java stream,

hashmap<string, list<data>> hemap = new hashmap<string, list<data>>(); (data hedata : obj) {     string id = hedata.getdata().getid() + hedata.getplandata().getcode()             + hedata.getplandata().getid();     if (!hemap.containskey(id)) {         citizenhelist = new arraylist<data>();          citizenhelist.add(hedata);         hemap.put(id, citizenhelist);      } else {         hemap.get(id).add(hedata);     } } 

i tried below code using stream, not succeed on this.

hemap=obj.stream().collect(collectors.tomap(t->getkey(t), obj.stream().collect(collectors.tolist())));  private string getkey(data hedata){     string id = hedata.getdata().getid() + hedata.getplandata().getcode()                     + hedata.getplandata().getid();     return id; } 

this job groupingby collector:

import static java.util.stream.collectors.groupingby;  map<string, list<data>> hemap = obj.stream().collect(groupingby(d -> getkey(d))); 

note use some unspecified implementations of map , list. currently, happens hashmap , arraylist, might change in future.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -