Java Question

java collections - keyset() vs entrySet() in map

I put a string array elements is a map where elements of string array is key and frequency of word is value, e.g.:

String[] args = {"if","it","is","to","be","it","is","up","me","to","delegate"};

then the map will have entries like
[ if:1 , it:2 .... ]

Set<String> keys = m.keySet();
System.out.println("keyset of the map : "+keys);

prints all keys:

Set<Map.Entry<String, Integer>> entrySet = m.entrySet();
Iterator<Map.Entry<String, Integer>> i = entrySet.iterator();
Map.Entry<String, Integer> element =;
System.out.println("Key: "+element.getKey()+" ,value: "+element.getValue());

prints all key values pairs :

Using entry set prints all values:

Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1

But the block of code below should print exactly the same output as above, but it does not:

Iterator<String> itr2 = keys.iterator();
//System.out.println(" ");
//System.out.println(m.get(" ");
System.out.println("Key: "" ,value: "+m.get(;

It prints:

Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1

But if we uncomment line 1 in the while loop i.e

System.out.println(" ");

and comment the line

System.out.println("Key: "" ,value: "+m.get(;

Then we get all keys:

If we use
, then the iterator doesnot have few keys!


Every call to the 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()) {