比较两个散列映射并打印交叉点
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);
我的问题是如何使用整数键值来比较两个哈希映射?我想在键值相同的情况下打印位图值。
使用 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());
}
}
您可以迭代 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
,那么解决方法就和mapB.keySet().retainAll(mapA.keySet());
一样简单。
这将只保留 mapB
中那些在 mapA
中具有相应键的条目,因为 keySet()
返回的集合由映射本身支持,对它将反映到地图上。
是的,我找到了解决方案...
if(mapB.containsKey(position)){
Log.e("bucky",mapB.get(position));}
位置表示整数值。
有 Java 8 个流 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);
我有两个哈希映射:一个包含整数键和字符串值。
另一个包含整数键和浮点值。
代码
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);
我的问题是如何使用整数键值来比较两个哈希映射?我想在键值相同的情况下打印位图值。
使用 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());
}
}
您可以迭代 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
,那么解决方法就和mapB.keySet().retainAll(mapA.keySet());
一样简单。
这将只保留 mapB
中那些在 mapA
中具有相应键的条目,因为 keySet()
返回的集合由映射本身支持,对它将反映到地图上。
是的,我找到了解决方案...
if(mapB.containsKey(position)){
Log.e("bucky",mapB.get(position));}
位置表示整数值。
有 Java 8 个流 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);