How to Iterate HashMap java

How to Iterate HashMap java

Answer: Below is demo class which shows different ways to iterate HashMap:

package com.javahonk.setTest;

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

public class HashMapIteration {

    public static void main(String[] args) {

    Map<String, String> map = new HashMap<String, String>();

    map.put("1", "First");
    map.put("2", "Second");
    map.put("3", "Third");
    map.put("4", "Fourth");
    map.put("5", "Five");

    System.out.println("Iterator Example 1\n");

    Iterator<Entry<String, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String,String> entry = (Map.Entry<String,String>) it.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        System.out.println("Key:" + key + ",Value: " + val);
        // it.remove(); // avoids a ConcurrentModificationException
    }

    System.out.println("\nIterator Example 2\n");

    Iterator<String> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String val = (String) map.get(key);
        System.out.println("Key:" + key + ",Value: " + val);
        // it.remove(); // avoids a ConcurrentModificationException
    }

    System.out.println("\nMap.Entry Example 3\n");

    for (Map.Entry<String,String> entry : map.entrySet()) {
        System.out.println("Key:" + entry.getKey() + ",Value: "
                + entry.getValue());
        // it.remove(); // avoids a ConcurrentModificationException
    }

    System.out
            .println("\nExample 4"
                    + ". If you're only interested in the keys, "
                    + "you can iterate through the keySet() of the map:\n");

    for (String key : map.keySet()) {
        System.out.println("Key:" + key);
    }

    System.out.println("\nExample 5"
            + ". If you only need the values, use values():\n");
    for (Object value : map.values()) {
        System.out.println("Value:" + value);
    }

    }

}

Output:
hashmap2

Leave a Reply

Your email address will not be published. Required fields are marked *