Java Joy: Merge Maps Using Stream API
Maps, meet Stream. Merging made simple.
Join the DZone community and get the full member experience.Join For Free
In Java, we can merge a key/value pair into a
Map with the
merge method. The first parameter is the key, the second the value, and the third parameter of the
merge method is a remapping function that is applied when the key is already present in the
Map instance. The remapping function has the value of the key in the original
Map and the new value. We can define in the function what the resulting value should be. If we return
null, the key is ignored.
If we want to merge multiple
Map instances, we can use the Stream API. We want to convert the
Map instances to a stream of
Map.Entry instances, which we then turn into a new
Map instance with the
toMap method from the class
toMap method also takes a remapping function when there is a duplicate key. The function defines what the new value is based on the two values of the duplicate key that was encountered. We can choose to simply ignore one of the values and return the other value. But we can also do some computations in this function, for example creating a new value using both values.
In the following example, we use the Stream API to merge multiple
Map instances into a new
Map using a remapping function for duplicate keys:
Written with Java 15.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.