Home > database >  How do I combine two HashMaps in java into one new HashMap with divided values?
How do I combine two HashMaps in java into one new HashMap with divided values?

Time:12-18

I'm trying to combine two HashMap's data to make a third HashMap. The keys from both would still be the same on the third HashMap.

However, the values in the PeopleAndTotal and PeopleAndDivider HashMap needs to be divided, so that the quotient can take it's place in the 3rd HashMap alongside its respective key.

(Also worth noting that the keys in the first both maps are the same.)

Here are the contents of the first two maps:

  1. PeopleAndTotal: {p1=20, p2=40, p3=9, p4=18, p5=20, p6=40}
  2. PeopleAndDivider: {p1=2, p2=2, p3=3, p4=3, p5=4, p6=4}

I need to make a third HashMap that'd print out like this:

  1. CombineMap: {p1=10, p2=20, p3=3, p4=6, p5=5, p6=10}

Here is what the code looks like so far:

import java.util.HashMap;

public class HashmapTest2 {

    public static void main(String[] args) {

        HashMap<String, Integer> PeopleAndTotal = new HashMap<String, Integer>();
        HashMap<String, Integer> PeopleAndDivider = new HashMap<String, Integer>();

        PeopleAndTotal.put("p1", 20);
        PeopleAndTotal.put("p2", 40);
        PeopleAndTotal.put("p3", 9);
        PeopleAndTotal.put("p4", 18);
        PeopleAndTotal.put("p5", 20);
        PeopleAndTotal.put("p6", 40);

        PeopleAndDivider.put("p1", 2);
        PeopleAndDivider.put("p2", 2);
        PeopleAndDivider.put("p3", 3);
        PeopleAndDivider.put("p4", 3);
        PeopleAndDivider.put("p5", 4);
        PeopleAndDivider.put("p6", 4);

        System.out.println(PeopleAndTotal);
        System.out.println(PeopleAndDivider);

        HashMap<String, Integer> CombineMap = new HashMap<String, Integer>();

        //Insert method here, How would I go about this?

        System.out.println("Expected Output for CombineMap should be");
        System.out.println("{p1=10, p2=20, p3=3, p4=6, p5=5, p6=10}");

        System.out.println(CombineMap);
    }
}

What's the best way to go about this?

CodePudding user response:

You would have to iterate over PeopleAndTotal and access the other map PeopleAndDivider to get the divider value for the same key. Then divide and put the result in the CombineMap under the same key.

for (Map.Entry<String, Integer> entry : PeopleAndTotal.entrySet()) {
    Integer total = entry.getValue();
    Integer divider = PeopleAndDivider.get(entry.getKey());
    CombineMap.put(entry.getKey(), total / divider)
}

CodePudding user response:

Here’s a one liner:

Map<String, Integer> CombineMap = PeopleAndTotal.entrySet().stream()
  .collect(toMap(Map.Entry::getKey, e -> e.getValue() / PeopleAndDivider.get(e.getKey())));
  •  Tags:  
  • java
  • Related