Reputation: 111
I have created two hashmaps and I want to iterate both of them inside the same for loop.
HashMap<String,Double> hashmapA = new HashMap<>();
HashMap<String,Double> hashmapB = new HashMap<>();
So, if I iterate the elements in hashmapA
as follows:
for(String map1:hashmapA.keyset()){
...
}
How can I iterate the values of hashmapB
inside the same loop? Actually, I don't want to use the inner loop.
Upvotes: 0
Views: 56
Reputation: 16457
If you just want to iterate over all keys:
Just create a new HashSet
out of the keys of the first Map
and add the keys of the second Map
:
Collection<Map.Entry<String,Double>> entries=new HashSet<>(hashmapA.entrySet());
keys.addAll(hashmapB.entrySet());
for(Map.Entry<String,Double> entry:entries){
String key=entry.getKey();
Double value=entry.getValue();
...
}
This can also be done using Java 8 Streams:
for(Map.Entry<String,Double> entry: Stream.concat(hashmapA.entrySet().stream(),hashmapB.entrySet().stream()){
String key=entry.getKey();
Double value=entry.getValue();
...
}
If you just want the intersection of the maps, you can use:
Collection<String> keys=new HashSet<>(hashmapA.keySet());
keys.retainAll(hashmapB.keySet());
for(String key:keys){
Double aValue=hashmapA.get(key);
Double bValue=hashmapB.get(key);
...
}
Or (with Streams):
for(String key: hashmapA.entrySet().stream().filter(k->hashmapB.containsKey(k))){
Double aValue=hashmapA.get(key);
Double bValue=hashmapB.get(key);
...
}
As @bsaverino stated in the comments:
Regarding your latest remark @Hami then just iterating over the keys of
hashmapA
and usinghashmapB.containsKey(...)
could have been enough.
The following will also work in your case:
for(String key:hashmapA.keySet()){
if(hashmapB.containsKey(key){
Double aVal=hashmapA.get(key);
Double bVal=hashmapB.get(key);
}
}
Upvotes: 1
Reputation: 40078
Iterator is one of the best choice either with keyset
or entrySet
Iterator hmIterator1 = hashmapA.entrySet().iterator();
Iterator hmIterator2 = hashmapB.entrySet().iterator();
while (hmIterator1.hasNext() && hmIterator2.hasNext()) {
hmIterator1.next();
hmIterator2.next();
}
Upvotes: 1