merge - Merging two Map<String, Integer> with Java 8 Stream API -
i have 2 (or more) map<string, integer>
objects. i'd merge them java 8 stream api in way values common keys should maximum of values.
@test public void test14() throws exception { map<string, integer> m1 = immutablemap.of("a", 2, "b", 3); map<string, integer> m2 = immutablemap.of("a", 3, "c", 4); list<map<string, integer>> list = newarraylist(m1, m2); map<string, integer> mx = list.stream()... // todo map<string, integer> expected = immutablemap.of("a", 3, "b", 3, "c", 4); assertequals(expected, mx); }
how can make test method green?
i've played collect
, collectors
while without success.
(immutablemap
, newarraylist
google guava.)
@test public void test14() throws exception { map<string, integer> m1 = immutablemap.of("a", 2, "b", 3); map<string, integer> m2 = immutablemap.of("a", 3, "c", 4); map<string, integer> mx = stream.of(m1, m2) .map(map::entryset) // converts each map entry set .flatmap(collection::stream) // converts each set entry stream, // "concatenates" in place of original set .collect( collectors.tomap( // collects map map.entry::getkey, // each entry based map.entry::getvalue, // on entries in stream integer::max // such if value exist // given key, max of old // , new value taken ) ) ; /* use following if want create map parallel streams map<string, integer> mx = stream.of(m1, m2) .parallel() .map(map::entryset) // converts each map entry set .flatmap(collection::stream) // converts each set entry stream, // "concatenates" in place of original set .collect( collectors.toconcurrentmap( // collects map map.entry::getkey, // each entry based map.entry::getvalue, // on entries in stream integer::max // such if value exist // given key, max of old // , new value taken ) ) ; */ map<string, integer> expected = immutablemap.of("a", 3, "b", 3, "c", 4); assertequals(expected, mx); }
Comments
Post a Comment