简体   繁体   English

根据Java中的键比较两个不同哈希图的值

[英]comparing values of two different hashmaps based on their key in java

I have two different hashmaps. 我有两个不同的哈希图。 Now I need to compare the hashmaps based on their keys.Like, 现在我需要根据哈希键比较哈希图。

HashMap1:
Key: BOF   Value: SAPF,754
Key: BOM   Value: SAPM,456
Key: BOL   Value: SAPL,987


HashMap2:
Key: LOF   Value: YTR,654
Key: BOL   Value: UHG,732

Now I want to compare all those entries in the hashmaps whose 'key's are same and return the difference between the second index of 'values' String[] 现在,我想比较“键”相同的哈希图中的所有条目,并返回“值” String []的第二个索引之间的差

Like here it should return: Key: BOL Value: SAPL,255 像这里这样它应该返回:键:BOL值:SAPL,255

(as 987-732=255) (如987-732 = 255)

How to do it? 怎么做?

map.keySet() will return set of keys in map. map.keySet()将返回地图中的键集。 Then you have to get value with this key from both map and find the difference. 然后,您必须使用这把钥匙从两个地图中获取价值,并找到不同之处。

Map<String, String[]> mp1 = //
Map<String, String[]> mp2 = //
Map<String, List<String>> res = new HashMap<>();
for (String key : mp1.keySet()) {
    int val1 = Integer.valueOf(mp1.get(key)[1]);
    int val2 = Integer.valueOf(mp2.get(key)[1]);
    List<String> resVal = new ArrayList<>();
    resVal.add(mp1.get(key)[0]);
    resVal.add(String.valueOf(val1-val2));
    res.put(key, resVal);
}
return res;

One more thing, you have check for existence. 还有一件事,您要检查是否存在。 Otherwise you will get NullPointerException 否则,您将获得NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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