Update: I might prefer the concise solution by Alexander Ivanchenko. I will leave this Answer posted as an interesting or educational alternative.
Your example data is flawed (repeated keys), so I crafted another set of data.
Map < String, Double > map1 =
Map.of(
"X1" , 1d ,
"X2" , 1d
);
Map < String, Double > map2 =
Map.of(
"X1" , 2d ,
"X2" , 2d ,
"X3" , 7d
);
Define a new Map
to hold results.
Map < String, Double > results = new HashMap <>();
Stream
& Map#getOrDefault
Process the two input maps by making a stream of each, joining those streams into a single stream. For each map entry in that stream, put the key into the new map, with a value of either the entry's value upon first occurrence or adding the entry's value to the previously put value.
Stream
.concat( map1.entrySet().stream() , map2.entrySet().stream() )
.forEach(
stringDoubleEntry ->
results.put(
stringDoubleEntry.getKey() , // key
results.getOrDefault( stringDoubleEntry.getKey() , 0d ) + stringDoubleEntry.getValue() ) // value
);
System.out.println( "results.toString() = " + results );
See this code run live at Ideone.com.
map = {X1=3.0, X2=3.0, X3=7.0}
Without streams
If not yet familiar with streams, you could instead use a pair of for-each loops to process each of the two input maps.
Process the first map.
for ( Map.Entry < String, Double > stringDoubleEntry : map1.entrySet() )
{
String k = stringDoubleEntry.getKey();
Double v =
results
.getOrDefault( stringDoubleEntry.getKey() , 0d ) // Returns either (A) a value already put into `results` map, or else (B) a default value of zero.
+ stringDoubleEntry.getValue();
results.put( k , v ); // Replaces any existing entry (key-value pair) with this pair.
}
And do the same for the second input map. The only difference here is the first line, map1.entrySet()
becomes map2.entrySet()
.
for ( Map.Entry < String, Double > stringDoubleEntry : map2.entrySet() )
{
String k = stringDoubleEntry.getKey();
Double v =
results
.getOrDefault( stringDoubleEntry.getKey() , 0d ) // Returns either (A) a value already put into `results` map, or else (B) a default value of zero.
+ stringDoubleEntry.getValue();
results.put( k , v ); // Replaces any existing entry (key-value pair) with this pair.
}