let's have multiple n maps with-> key:string val:object
i want merge of them 1 big map , , sum object filed values:
for instance:
import java.util.hashmap; import java.util.map; /** * created vitaly on 21/07/2016. */ public class merge { static map<string, container> map1 = new hashmap<>(); static map<string, container> map2 = new hashmap<>(); static map<string, container> map3 = new hashmap<>(); public void initmaps() { map1.put("aaa", new container(1, "title_aaa")); map1.put("bbb", new container(4, "title_bbb")); map2.put("ccc", new container(7, "title_ccc")); map2.put("aaa", new container(10, "title_aaa")); map3.put("aaa", new container(13, "title_aaa")); map3.put("bbb", new container(16, "title_bbb")); ... mapn.put(... } class container { public container(int val1, string title) { this.val1 = val1; this.title = title; } int val1; string title; } public static void main(string[] args) { merge.mergemaps(map1, map2, map3); } public static map<string, container> mergemaps(map... maps) { /** * how create 1 merged map sums values */ // result should be: //map(aaa, {24,title_aaa ) //1+10+13 //map(bbb, {20,title_ccc ) //4+16 //map(ccc, {7,title_ccc ) //7 return map; } }
prefer java 8 doesn't matter :)
thanks lot!
stream on different maps, flatmap them one. use collectors#groupingby
sort them via different values (aaa, bbb, etc.). stream on result of again create new container
objects summed values.
finally, use collectors.tomap
create map need.
if have question, don't hesitate.
public static map<string, container> mergemaps(map<string, container>... maps) { map<string, container> map = arrays.stream(maps) .flatmap(x -> x.values().stream()) .collect(collectors.groupingby(v -> v.gettitle().substring(6))) .entryset().stream() .map(e -> new merge().new container(e.getvalue().stream().maptoint(x -> x.getval()).sum(), e.getvalue().get(0).gettitle())) .collect(collectors.tomap(e -> ((container) e).gettitle().substring(6), e -> e)); return map; }
and here output
{aaa=24 : title_aaa, ccc=7 : title_ccc, bbb=20 : title_bbb}
Comments
Post a Comment