Maps, meet Stream. Merging made simple.
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 Collectors
. The 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.
#java #tutorial #merge #java stream api #java 15 #java maps