我有两个哈希映射:一个包含整数键和字符串值。
另一个包含整数键和浮点值。
法典
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
中保留那些在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);