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

46 views Asked by At

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.

2

There are 2 answers

0
f1sh On BEST ANSWER

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.

0
WJS On

As @f1sh suggested, just use one map and use its key to get the other value from the second map. Here is a stream approach.

Map<String, Values> map = map1.entrySet().stream()
         .collect(Collectors.toMap(Entry::getKey,
                 e -> new Values(BigDecimal.valueOf(e.getValue()),
                         BigDecimal.valueOf(map2.get(e.getKey())))));

 map.entrySet().forEach(System.out::println);

prints

A=123.1, 543.5
B=345.2, 432.2
C=678.3, 654.3