Home > Back-end >  Best way to multiply corresponding values in two maps
Best way to multiply corresponding values in two maps

Time:11-14

How can you multiply the values of map1 to it's corresponding values in map2? I've tried two for loops, but it iterates through both maps 16 times. Assuming that both maps will always be the same length.

Map<String, Integer> map1= new HashMap<>();
Map<String, Integer> map2= new HashMap<>();

map1.put("one", 1);
map1.put("two", 2);
map1.put("three", 3);
map1.put("four", 4);

map2.put("one", 1);
map2.put("two", 2);
map2.put("three", 3);
map2.put("four", 4);

//map1 = {(one, 1), (two, 2)... etc
//map2 = the same

for(Integer num:map1.values()){
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

I'm doing something wrong. I would like to multiply each value and get that sum i.e. (1 * 1) (2 * 2)...

CodePudding user response:

Stream the entries, multiply each’s value by its matching value in the other map, then sum:

int sum = map1.entrySet().stream()
  .mapToInt(e -> e.getValue() * map2.get(e.getKey()))
  .sum();

CodePudding user response:

Key/value pairs in java maps are unordered. There is no guarantee that when you iterate over the values below that you will get the values in the same order.

for(Integer num:map1.values())[
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

The following would do it

for (Map.Entry<String, Integer> entry : map1.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    total  = value * map2.get(key);
}
System.out.println(total);

The above code is assuming that you always have the keys from map1 in map2 ! The complexity of this is O(n)* O(1), where n is the number of keys in map1. Accessing the values in map2 is considered constant.

CodePudding user response:

You should be iterating the keys of one map, get related value from the other map (possibly using getOrDefault to return a default value for the missing ket) and calculate the total of their products:

int total = 0;

for (String key : map1.keySet()) {
    total  = map1.get(key) * map2.getOrDefault(key, 0);
}

Similar solution using Stream API:

int total = map1.entrySet().stream()
    .mapToInt(e -> e.getValue() * map2.getOrDefault(e.getKey(), 0))
    .sum();
  • Related