java collections - keyset() vs entrySet() in map
Every call to the Iterator.next()
moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry
implementations usually implement the toString()
method, so you don't have to print the key-value pair manually.
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry);
}
Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.
Iterator<String> itr2 = keys.iterator();
while(itr2.hasNext()){
String v = itr2.next();
System.out.println("Key: "+v+" ,value: "+m.get(v));
}
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.