为什么结合两个hashMap的结果不是corecct?
问题描述:
我有两个HashMap
,第一个有3149条记录,第二个5440条记录,当我合并它们时,结果尺寸小于3149 + 5440。为什么以及如何解决它?为什么结合两个hashMap的结果不是corecct?
Map<String,String> bigMap = new HashMap<String, String>();
bigMap.putAll(hashMap1);
bigMap.putAll(hashMap2);
int j = 0;
for (Map.Entry<String, String> entry : bigMap.entrySet()) {
System.out.println(j++);
}
我也cheched与此代码,以确保如果有一些共同的关键。
for (Map.Entry<String, String> entry : readCsv(hashMap1).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(entry.getKey().equals(hashMap2).get(key))){
System.out.println(i++);
}
}
答
你hashMap1
和hashMap
可能有一些相同的密钥。这就是为什么有些条目被具有相似键的其他条目覆盖的原因。
答
如果你在地图上有相同的密钥,那么这是可以预料的。密钥在地图中必须是唯一的。如果使用已存在的键将值放入映射中,则现有值将被覆盖。
答
要找到共同的键,你可以做
Set<String> common = new HsahSet<String>(hashMap1.keySet());
common.retainAll(hashMap2.keySet());
System.out.println("Common Keys " + common);
没有你的代码的其余部分就很难说了。你对这两张地图的记录数是否积极? – mcfinnigan 2012-02-01 10:12:04
小于3149 + 5440,或小于3149?如果'hashMap1'和'hashMap2'共享密钥,则只有这些密钥的'hashMap2'值会出现在'bigMap'中。 – Vlad 2012-02-01 10:12:39
也许是因为hashMap1和hashMap2有一些共同的密钥? – Pengtuzi 2012-02-01 10:12:49