繁体   English   中英

比较两个哈希映射和打印交集

[英]Comparing two hash-maps and printing intersections

我有两个哈希映射:一个包含一个整数键和字符串值。

另一个包含一个整数键和浮点值。

代码

Map<Integer,String> mapA = new HashMap<>();
mapA.put(1, "AS");
mapA.put(2, "Wf");

Map<Integer,Float> mapB = new HashMap<>();
mapB.put(2, 5.0f);
mapB.put(3, 9.0f);

我的问题是如何使用整数键值比较两个哈希映射? 当键值相同时,我想打印位图值。

例如,您可以迭代mapA的键并检查它是否存在于mapB然后将该值添加到第三个mapC中。

Map<String, float> mapC = new HashMap<String, float>();

for (Integer key : mapA.keySet()) {
    if (mapB.containsKey(key)) {
        mapC.put(mapA.get(key), mapB.get(key));
    }
}

使用 mapB 迭代器比较两个映射中的键。

Iterator<Entry<Integer, Float>> iterator = mapB.entrySet().iterator();
    while(iterator.hasNext()) {
        Entry<Integer, Float> entry = iterator.next();
        Integer integer = entry.getKey();
        if(mapA.containsKey(integer)) {
            System.out.println("Float Value : " + entry.getValue());
        }
    }

如果允许修改mapB ,那么解决方案就像mapB.keySet().retainAll(mapA.keySet());一样简单mapB.keySet().retainAll(mapA.keySet()); .

这只会在mapB中保留那些在mapB中具有相应键的mapA ,因为keySet()返回的集合由映射本身支持,对其所做的任何更改都将反映到映射中。

是的,我得到了解决方案...

 if(mapB.containsKey(position)){
          Log.e("bucky",mapB.get(position));}

位置表示整数值。

使用 Java 8 Streams API:

Map<Integer, Object> matchInBothMaps = mapA
                                            .entrySet()
                                            .stream() 
                                            .filter(map -> mapB.containsKey(map.getKey())) 
                                            .collect(Collectors.toMap(map -> map.getKey(), 
                                                                      map -> map.getValue()));
        
System.out.println(matchInBothMaps);

暂无
暂无

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

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