Map

Map Interface also extends the Collection Interface. Map mean that it cares about the unique identifier i.e Map maps the unique key(ID) to a specific value.The Map implementation let do things like search value based on the key. The Map interface is implemented by

  • HashMap
  • Hashtable
  • TreeMap
  • LinkedHashMap
Difference between HashMap, Hashtable, TreeMap and LinkedHashMap :
HashMap Hashtable TreeMap LinkedHashMap
A HashMap is unsorted and unordered Map. A Hashtable is a legacy class. A TreeMap is a sorted Map. LinkedHashMap maintain the insertion order.
Inherit from Map. Inherit from Map. Inherit from SortedMap.But from Java 6 onwards TreeMap implements NavigableMap Inherit from Map.
HashMap is faster in adding and removing values. Hashtable is slower than HashMap TreeMap is slower as it first sort the values. LinkedHashMap is faster in iteration among values

Syntax of HashMap, Hashtable, TreeMap and LinkedHashMap :
Map Create Add Traverse
HashMap HashMap name=new HashMap(); name.put("name1","Peter"); name.add("name2","James"); Set set =name.keySet(); Iterator i =set.iterator();
Hashtable Hashtable name=new Hashtable(); same as above Enumeration e =name.elements();
TreeMap TreeMap name=new TreeMap(5); same as above Set set =name.keySet(); Iterator i =set.iterator();
LinkedHashMap LinkedHashMap name=new LinkedHashMap(5); same as above same as above
Example to show HashMap insertion :
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
	public static void main(String[] args) {
		 Map map=new HashMap();
		 map.put("name","James");
		 map.put("address","USA");
		 map.put("number",90121);
		 System.out.println(map.get("name"));
		 System.out.println(map);
	}
}