[英]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.我需要根据 PeopleAndNumbers 和 PeopleAndGroups 哈希图中的值制作第三个 HashMap。 But the third HashMap would only have the 3 groups as keys and the total amounts from the people in that group as values.
但是第三个 HashMap 将只有 3 个组作为键,而该组中的人的总数作为值。
(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}
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}
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:我需要制作第三个 HashMap 打印出来是这样的:
CombineMap: {GroupA=3, GroupB=6, GroupC=3}
组合地图:
{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()))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.