[英]Comparing two hash-maps and printing intersections
I have two hash maps: one contains an Integer key and String value.我有两个哈希映射:一个包含一个整数键和字符串值。
The other contains an Integer key and float value.另一个包含一个整数键和浮点值。
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);
My question is how to compare the two hash maps using the integer key value?我的问题是如何使用整数键值比较两个哈希映射? I want to print the bitmap value when the key values are the same.当键值相同时,我想打印位图值。
You can just iterate on the keys of mapA
and check if it is present in mapB
then add the value to a third mapC
for example.例如,您可以迭代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));
}
}
Compare keys in two map by using mapB iterator.使用 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());
}
}
If you are allowed to modify mapB
, then the solution is as simple as mapB.keySet().retainAll(mapA.keySet());
如果允许修改mapB
,那么解决方案就像mapB.keySet().retainAll(mapA.keySet());
一样简单mapB.keySet().retainAll(mapA.keySet());
. .
This will only leave those entries in mapB
that have a corresponding key in mapA
, because the set returned by keySet()
is backed by the map itself, any changes made to it will be reflected to the map.这只会在mapB
中保留那些在mapB
中具有相应键的mapA
,因为keySet()
返回的集合由映射本身支持,对其所做的任何更改都将反映到映射中。
yes i got solution...是的,我得到了解决方案...
if(mapB.containsKey(position)){
Log.e("bucky",mapB.get(position));}
position means integer value.位置表示整数值。
With Java 8 Streams API:使用 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.