Search code examples
javahashmapcollectors

Merging two hashmaps with their values combined as object of specific class


I have a class like

public class Values {

    BigDecimal a;
    BigDecimal b;
}

And two maps with the same keys like

Map<String, Double> map1 = Map.of("A", 123.1, "B", 345.2, "C", 678.3);

Map<String, Double> map2 = Map.of("A", 543.5, "B", 432.2, "C", 654.3);

I want to merge those maps into one Map<String, Values> converting Doubles to BigDecimals on the way How can I achieve that? And maybe it's even possible without explicitly creating third map?

Example of desired output (Doubles are now BigDecimals as fields a and b of Values class)

Map<String, Values> map3
"A", {123.1, 543.5}
"B", {345.2, 345.2}
"C", {678.3, 654.3}

Tried solutions from close topics with stream and collectors and i guess i just cant figure it out.


Solution

  • Just iterate over one of the input Maps:

        private static Map<String, Values> mergeMaps(Map<String, Double> map1Map<String, Double> map2) {
            Map<String, Values> result = new HashMap<>();
            for(Map.Entry<String, Double> e1:map1.entrySet()) {
                BigDecimal a = BigDecimal.valueOf(e1.getValue());
                BigDecimal b = BigDecimal.valueOf(map2.get(e1.getKey()));
                result.put(e1.getKey(), new Values(a, b));
            }
            return result;
        }
    

    This makes use of a AllArgsConstructor of Values which can be easily done if you make use of java's record:

    public record Values (BigDecimal a, BigDecimal b){}
    

    Please note that this code assumes that both input maps have the same set of keys.