Iterate map java

Map is an interface which maps keys to values. Map can’t contain duplicate keys also every key should map to one value. Map is replacement of Dictionary class which is not interface but totally abstract class.

Map interface provides three collection views which allows map’s contents be viewed as set of keys, collection of values and set of key-value pair mappings. The order of map is defined as order in which iterators on the map’s collection views return their elements. Map implementations TreeMap class which makes guarantees as to their order but others like HashMap class do not supports ordering of the element

Below example shows you different ways to Iterate map java:

package com.javahonk.list;

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

public class IterateHashMapExample {

	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 entry = (Map.Entry) 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 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:

Iterate over map java

Reference: Oracle java documentation

Leave a Reply

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