Showing posts with label Iterate. Show all posts
Showing posts with label Iterate. Show all posts

Friday, May 2, 2014

Iterate over each Entry in HashMap in Java Or loop Map to remove Entries

Example Class: HashMapIterator.java

package com.pkm.annotation;

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

/**
 *
 * @author Pritom
 */
public class HashMapIterator {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1", "Value 1");
        map.put("key2", "Value 2");
        map.put("key3", "Value 3");
        map.put("key4", "Value 4");
        map.put("key5", "Value 5");
        
        /* Using Iterator */
        System.out.println("Using Iterator");
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iterator.next();
            System.out.println("Key: " + mapEntry.getKey() + ", Value: " + 
                    mapEntry.getValue());
            if(mapEntry.getKey().toString().equals("key3")) {
                /* Removing without ConcurrentModificationException */
                iterator.remove(); 
            }
        }
        
        /* Using Direct Entry Set */
        System.out.println("\nUsing Direct Entry Set");
        for (Object entry : map.entrySet()) {
            Map.Entry mapEntry = (Map.Entry) entry;
            System.out.println("Key : " + mapEntry.getKey() + ", Value : "
                    + mapEntry.getValue());
        }
        
        /* Using Direct Key Set */
        System.out.println("\nUsing Direct Key Set");
        for (Object entry : map.keySet()) {
            System.out.println("Key : " + entry + ", Value : "
                    + map.get(entry));
        }
    }
}

Example Output:

Using Iterator
Key: key4, Value: Value 4
Key: key3, Value: Value 3
Key: key5, Value: Value 5
Key: key2, Value: Value 2
Key: key1, Value: Value 1

Using Direct Entry Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Using Direct Key Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1