Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java Programming

Map interface

A Map is a collection that keeps key-value pairs. Using a map we can map keys to values. A map cannot have have duplicate keys and a key can map to only one value.

Map implementation classes :

Map has implementation classes - HashMap, TreeMap and LinkedHashMap. In HashMap oredering of the elements is not preserved, while in LinkedHashMap oredering of the elements is preserved on the basis of the inserson. In TreeMap, key-value pair is maintained in the ascending sorting order of the key. To add an object as a key to the TreeMap that class should implement Comparable interface which in turn forces to implement compareTo() method which in turn contains the sorting order definition. We also have Thread Safe implementations for HashMap - SynchronizedHashMap and ConcurrentHashMap


Map Interface Basic Operations

Map provides the following methods to perform basic operations:
  • put() - To add the key-value pair in the Map.
  • get() – To get the value corresponding to the key. Key is passed to this method and value is returned.
  • containsKey() – To check if the given key exits in the Map.
  • containsValue() – To check if the given value exists in the Map.
  • size() – To check the size of the Map i.e how many key-value pair exists in the Map.
  • isEmpty() – To check if the Map is empty.

In the below sample program, using a map to store "name" and "country" values pairs. "name" is the key to the map and "country" is the value. After storing, printing the values corresponding to the keys one by one.

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


public class MapTest {

	
	
	public static void main(String[] args) {
	
		Map<String, String> nameCountryMap = new HashMap<String, String>();
		
		//using put() method to store name(key) and country(value) values 
		nameCountryMap.put("Ram", "India");
		nameCountryMap.put("John", "Jermany");
		nameCountryMap.put("Nick", "USA");
		
		String country = nameCountryMap.get("Ram");
		System.out.println("Ram's country is "+country);
		
		country = nameCountryMap.get("John");
		System.out.println("John's country is "+country);
		
		country = nameCountryMap.get("Nick");
		System.out.println("Nick's country is "+country);
		
	}
	
}




Traversing Through a Map :

We can traverse a Map using EntrySet or KeySet class -

Using EntrySet
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class TraverseMapUsingEntrySet {
	public static void main(String args[]) {
		// creating hash map
		HashMap<Integer, String> map = new HashMap<Integer, String>();

		// Adding key-value pairs to the HashMap
		map.put(1, "India");
		map.put(2, "US");
		map.put(3, "UK");
		map.put(4, "China");

		Set<Entry<Integer, String>> entrySet = map.entrySet();
		//Using entrySet we can iterate over key-value pairs using 
		//for-each construct or iterator or aggregate functions
		
		//Iterating using for-each construct
		for (Entry<Integer, String> entry : entrySet) {
			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
		}

		System.out.println();
		
		//Traversing using iterator
		Iterator<Entry<Integer, String>> itr=entrySet.iterator();
		while (itr.hasNext()) {
			Entry<Integer,String> entry = (Entry<Integer,String>) itr.next();
			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
		}
		
	}
}


Using KeySet
import java.util.HashMap;
import java.util.Set;
public class TraversalUsingKeySet {
	public static void main(String args[]) {
		// creating hash map
		HashMap<Integer, String> map = new HashMap<Integer, String>();

		// Adding key-value pairs to the HashMap
		map.put(1, "India");
		map.put(2, "US");
		map.put(3, "UK");
		map.put(4, "China");

		Set<Integer> keySet = map.keySet();
		for (Integer key : keySet) {
			
			System.out.println("Key = "+key+", Value = "+map.get(key));
		}
	}
}