[英]How do I combine two HashMaps in java into one new HashMap with divided values?
I'm trying to combine two HashMap's data to make a third HashMap.我正在尝试结合两个 HashMap 的数据来制作第三个 HashMap。 The keys from both would still be the same on the third HashMap.两者的密钥在第三个 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.但是,PeopleAndTotal 和 PeopleAndDivider HashMap 中的值需要除以,以便商可以在第三个 HashMap 旁边与其各自的键一起出现。
(Also worth noting that the keys in the first both maps are the same.) (还值得注意的是,前两个地图中的键是相同的。)
Here are the contents of the first two maps:以下是前两张地图的内容:
{p1=20, p2=40, p3=9, p4=18, p5=20, p6=40}
PeopleAndTotal: {p1=20, p2=40, p3=9, p4=18, p5=20, p6=40}
{p1=2, p2=2, p3=3, p4=3, p5=4, p6=4}
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:我需要制作第三个 HashMap 打印出来是这样的:
{p1=10, p2=20, p3=3, p4=6, p5=5, p6=10}
组合映射: {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? go 关于这个的最佳方法是什么?
You would have to iterate over PeopleAndTotal and access the other map PeopleAndDivider to get the divider value for the same key.您必须遍历 PeopleAndTotal 并访问另一个 map PeopleAndDivider 才能获得相同键的分隔符值。 Then divide and put the result in the CombineMap under the same key.然后将结果划分并放在同一key下的CombineMap中。
for (Map.Entry<String, Integer> entry : PeopleAndTotal.entrySet()) {
Integer total = entry.getValue();
Integer divider = PeopleAndDivider.get(entry.getKey());
CombineMap.put(entry.getKey(), total / divider)
}
Here's a one liner:这是一个衬里:
Map<String, Integer> CombineMap = PeopleAndTotal.entrySet().stream()
.collect(toMap(Map.Entry::getKey, e -> e.getValue() / PeopleAndDivider.get(e.getKey())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.