I have two (or more) Map<String, Integer>
objects. I'd like to merge them with Java 8 Stream API in a way that values for common keys should be the maximum of the 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 I make this test method green?
I've played with collect
and Collectors
for a while without any success.
(ImmutableMap
and newArrayList
are from Google Guava.)
Using StreamEx you can do:
This covers the general case for any size list and should work with any types, just swap out the
Integer::max
and/orHashMap::new
as desired.If you don't care which value comes out in a merge, there's a much cleaner solution:
And as generic methods:
I've created a visual representation of what @srborlongan did, for anyone who might be interested.
I added my contribution to the proton pack library which contains utility methods for the Stream API. Here's how you could achieve what you want:
Basically
mergeKeys
will collect the key-value pairs in a new map (providing a merge function is optional, you'll end up with aMap<String, List<Integer>>
otherwise) and recallstream()
on theentrySet()
to get a newMapStream
. Then usecollect()
to get the resulting map.