Thursday, 11 August 2016

What are different ways of iterating over keys, values and entry in Map?

What are different ways of iterating over keys, values and entry in Map?

Answer: 
Create and put key-value pairs in HashMap

package com.tutorial4u;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapDemo {
     public static void main(String[] args) {
           Map hashMap = new HashMap();
           hashMap.put(11, "CSS");
           hashMap.put(21, "IT");
           hashMap.put(31, "ECE");
           hashMap.put(41, "EEE");
     }
    
}

Iterate over keys :-

hashMap.keySet().iterator() method returns iterator to iterate over keys in HashMap.



Iterator keyIterator =hashMap.keySet().iterator();
           while(keyIterator.hasNext()){
           System.out.println(keyIterator.next());
       }

/*OUTPUT

21
41
11

31
*/
Iterate over values :-


hashMap.values().iterator() method returns iterator to iterate over keys in HashMap.


Iterator valueIterator=hashMap.values().iterator();
           while(valueIterator.hasNext()){
           System.out.println(valueIterator.next());
       }

/*OUTPUT

IT
EEE
CSS

ECE
*/

Iterate over Entry-


hashMap.entrySet().iterator() method returns iterator to iterate over keys in HashMap.

Iterator entryIterator=hashMap.entrySet().iterator();
           while(entryIterator.hasNext()){
           System.out.println(entryIterator.next());
       }

/*OUTPUT
21=IT
41=EEE
11=CSS
31=ECE

*/

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...