简体   繁体   中英

How do I put in the values (of different data types) from two HashMaps with the same keys into a new third HashMap?

I need to make a third HashMap based off the values from the PeopleAndNumbers and PeopleAndGroups hashmaps. But the third HashMap would only have the 3 groups as keys and the total amounts from the people in that group as values.

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

Here are the contents of the first two maps:

PeopleAndNumbers: {p1=1, p2=3, p3=2, p4=3, p5=1, p6=2}

PeopleAndGroups: {p1=GroupA, p2=GroupB, p3=GroupC, p4=GroupB, p5=GroupC, p6=GroupA}

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

CombineMap: {GroupA=3, GroupB=6, GroupC=3}

Here is what the code looks like so far:

import java.util.HashMap;

public class HashmapTest {

        public static void main(String[] args) {
            
            HashMap<String, Integer> PeopleAndNumbers = new HashMap<String, Integer>();

            HashMap<String, String> PeopleAndGroups = new HashMap<String, String>();

            PeopleAndNumbers.put("p1", 1);
            PeopleAndNumbers.put("p2", 3);
            PeopleAndNumbers.put("p3", 2);
            PeopleAndNumbers.put("p4", 3);
            PeopleAndNumbers.put("p5", 1);
            PeopleAndNumbers.put("p6", 2);

            PeopleAndGroups.put("p1","GroupA");
            PeopleAndGroups.put("p2","GroupB");
            PeopleAndGroups.put("p3","GroupC");
            PeopleAndGroups.put("p4","GroupB");
            PeopleAndGroups.put("p5","GroupC");
            PeopleAndGroups.put("p6","GroupA");

            System.out.println(PeopleAndNumbers);
            System.out.println(PeopleAndGroups);

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

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

            System.out.println("Expected Output for CombineMap should be");
            System.out.println("{GroupA=3, GroupB=6, GroupC=3}");

            System.out.println(CombineMap);
        }
    }

Without streams:

for (Map.Entry<String, Integer> entry : PeopleAndNumbers.entrySet()) { //or iterate over peaopleAndGroups..
  CombineMap.put(PeopleAndGroups.get(entry.getKey()), entry.getValue()); // put replaces (if) existing key 
}

If I understand you correctly, you want to sum Numbers by Group, using the common keys to join them. If so, you can do it pretty easily with streams:

Map<String, Integer> combined = PeopleAndGroups.entrySet()
        .stream()
        .collect(Collectors.groupingBy(e -> e.getValue(),
                Collectors.summingInt(e -> PeopleAndNumbers.get(e.getKey()))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM