Recent Tutorials and Articles
    Introduction to Map in Java
    Published on: 2018-05-25 16:05:39

    This tutorial introduces you to Map interface and it's implementation classes such as HashMap, LinkedHashMap and TreeMap along with explaining their characteristics and properties.

    Since this tutorial is using Generics so it is expected that reader has got decent knowledge of Generics. If you are new to Generics, you are recommended to read this tutorial first - Introduction to Generics

     

    Map, also known as associate array, is an object that stores the data in form of keys and values. In Java, maps are represented using Map interface which is not an extension of the collection interface. It rather has its own interface hierarchy and has got following specifications -

    1. Map can not contain duplicate keys where each key maps to one value.
    2. Map stores all of its data in a Set of type java.util.Map.Entry wherein each Entry is responsible for storing a key-value pair. This set of entries is generally referred as entry set.
    3. Map interface contains methods for operating on a single operations such as adding, getting, removing a key value pair. It also contains the methods for bulk operations such as adding and removing another map.

    The Java platform contains three general-purpose Map implementations: HashMap, LinkedHashMap, and TreeMap. Their behavior and performance are precisely analogous to HashSet, TreeSet, and LinkedHashSet, as described in Set tutorial here.

    1. HashMap
      1. HashMap is a hash table based implementation of Map which uses hashing technique to store its Entry elements.
      2. HashMap can be cloned and serialized as it implements Cloneable and Serializable interfaces respectively.
      3. HashMap permits null key (since keys has to be unique, you would only be able to have one null key) and null values.
      4. HashMap is not synchronized but If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally (Map map = Collections.synchronizedMap (new HashMap (...)) ;
      5. An instance of HashMap has two parameters initial capacity and load factor. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method.
      6. The iterators returned by this class is fail-fast resulting into ConcurrentModificationException if it is modified by a thread while other thread is iterating over it.
    2. LinkedHashMap
      1. LinkedHashMap can be cloned and serialized as it implements Cloneable and Serializable interfaces respectively.
      2. The orders of its elements are based on the order in which they were inserted (maintains insertion order). The insertion order is not affected if a key is re-inserted into the map.
      3. LinkedHashMap maintains a doubly-linked list running through all of its entries in it.
      4. LinkedHashMap implementations is not synchronized.
      5. The iterators returned by this class is fail-fast resulting into ConcurrentModificationException if it is modified by a thread while other thread is iterating over it.
    3. TreeMap
      1. TreeMap can be cloned and serialized as it implements Cloneable and Serializable interfaces respectively.
      2. It cannot have null key but can have multiple null values
      3. Entry elements in TreeMap are sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
      4. TreeMap class use four constructors (TreeMap (), TreeMap (Comparator comp), TreeMap (Map map), TreeMap (SortedMap sortedmap ) )
      5. TreeMap implementation is not synchronized.
      6. The iterators returned by this class is fail-fast resulting into ConcurrentModificationException if it is modified by a thread while other thread is iterating over it.

    As a best practice, we should always use the reference variables for Map interface as it makes it easy to switch from one implementation to another implementation of Map interface.

    MapInterfaceDemo.java
    package com.sts.allprogrammingtutorials.collections;
    
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.TreeMap;
    
    public class MapInterfaceDemo {
    
    	public static void main(String[] args) {
    
    		Map<Integer, String> hm = new HashMap<Integer, String>();
    
    		hm.put(100, "Amit");
    		hm.put(101, "Vijay");
    		hm.put(102, "Rahul");
    		
    		System.out.println ("HashMap maintains no order");
    		System.out.println ("Result for HashMap is:- " + hm);
    		
    		hm = new LinkedHashMap<Integer, String>();
    		
    		hm.put(100, "Amit");
    		hm.put(101, "Vijay");
    		hm.put(102, "Rahul");
    		
    		System.out.println ("LinkedHashMap maintains insertion order");
    		System.out.println ("Result for LinkedHashMap is:- " + hm);
    		
    		Map<Integer, String> hm1 = new TreeMap<Integer, String>();
    
    		hm1.put(100, "Amit");
    		hm1.put(102, "Vijay");
    		hm1.put(101, "Rahul");
    		
    		System.out.println ("TreeMap maintains natural(ascending) order");
    		System.out.println ("Result for TreeMap is:- " + hm1);
    		
    	}
    }
    
    
    Output:
    HashMap maintains no order
    Result for HashMap is:- {102=Rahul, 100=Amit, 101=Vijay}
    LinkedHashMap maintains insertion order
    Result for LinkedHashMap is:- {100=Amit, 101=Vijay, 102=Rahul}
    TreeMap maintains ascending order
    Result for TreeMap is:- {100=Amit, 101=Rahul, 102=Vijay}
    
    

    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Published on: 2018-05-25 16:05:39

    Comment Form is loading comments...