title: java collections - keyset() vs entrySet() in map
body: <p>I put a string array elements is a  map  where elements of string array is key and frequency of word is value, e.g.:</p>
  
  <pre><code>String[] args = {"if","it","is","to","be","it","is","up","me","to","delegate"};
  </code></pre>
  
  <p>then the map will have entries like <code>[ if:1, it:2 .... ]</code></p>
  
  <pre><code>Set&lt;String&gt; keys = m.keySet();
  System.out.println("keyset of the map : "+keys);
  </code></pre>
  
  <p>prints all keys: <code>"if","it","is","to","be","it","is","up","me","to","delegate"</code></p>
  
  <pre><code>Set&lt;Map.Entry&lt;String, Integer&gt;&gt; entrySet = m.entrySet();
  Iterator&lt;Map.Entry&lt;String, Integer&gt;&gt; i = entrySet.iterator();
  while(i.hasNext()){
      Map.Entry&lt;String, Integer&gt; element = i.next();
      System.out.println("Key: "+element.getKey()+" ,value: "+element.getValue());
  }
  </code></pre>
  
  <p>prints all key values pairs :</p>
  
  <p>Using entry set prints all values:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>But the block of code below should print exactly the same output as above, but it does not:</p>
  
  <pre><code>Iterator&lt;String&gt; itr2 = keys.iterator();
  while(itr2.hasNext()){
      //System.out.println(itr1.next()+" ");
      //System.out.println(m.get(itr1.next())+" ");
      System.out.println("Key: "+itr2.next()+" ,value: "+m.get(itr2.next()));
  }
  </code></pre>
  
  <p>It prints:</p>
  
  <pre><code>Key: if ,value: 2
  Key: is ,value: 2
  Key: be ,value: 1
  Key: me ,value: 1
  </code></pre>
  
  <p>But if we uncomment line 1 in the while loop i.e     </p>
  
  <pre><code>System.out.println(itr1.next()+" ");
  </code></pre>
  
  <p>and comment the line     </p>
  
  <pre><code>System.out.println("Key: "+itr2.next()+" ,value: "+m.get(itr2.next()));
  </code></pre>
  
  <p>Then we get all keys: <code>{"if","it","is","to","be","it","is","up","me","to","delegate"};</code></p>
  
  <p>If we use <code>m.get()</code> with <code>itr2.next()</code>, then the iterator does not have few keys!</p>