Map Collections in Java

Map Collections in Java with Examples

In this article, I am going to discuss Map Collections in Java with Examples. Please read our previous article where we discussed Queue Collections in Java with Examples. As part of this article, we are going to discuss the following pointers in detail which are related to Java Map Collections.

  1. Map Interface in Java
  2. Methods of Map Interface
  3. HashMap Collection in Java
  4. Hashtable Collection in Java
  5. LinkedHashMap Collection in Java
  6. TreeMap Collection in Java
Map Interface in Java:

A map is a data structure that supports the key-value pair mapping for the data. Each key and value pair is known as an entry. A Map contains unique keys. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings.

A map is useful if there is data and we wish to perform operations on the basis of the key. The Map interface of the Java collections framework provides the functionality of the map data structure.

Map Interface Hierarchy in Java

Map Interface Hierarchy in Java

Methods of Map Interface
  1. V put(K obj, V obj): This method is used to add a new key-value pair into the Map.
  2. V putAll(): Inserts all the entries from the specified map to this map.
  3. V putIfAbsent(K obj, V obj): Inserts the association of the key K is not already associated with the value V.
  4. V get(K obj): This method returns the Value object of the specified key. If the specified key is not available then it returns null.
  5. V getOrDefault(K obj, defaultValue): Returns the value associated with the specified key K. If the key is not found, it returns the defaultValue.
  6. V replace(K, V): Replace the value of the key K with the new specified value V.
  7. V replace(K, oldValue, newValue): Replaces the value of the key K with the new value newValue only if the key K associated with the value oldValue.
  8. V remove(K): this method removes the specified key along with its value.
  9. V remove(K, V): Removes the entry from the map that has key K associated with value V.
  10. int size(): this method returns the count of the number of Key-Value pairs available in the Map.
  11. boolean isEmpty(): This method returns true if Map not containing any Key-Value pairs otherwise it returns false.
  12. void clear(): This method clears all the Key-value pairs of the map.
  13. Set keyset(): This method returns all the keys available in the Map separately in the form of Set.
  14. Set entrySet(): This method returns all the Key-Value or entities available in the Map separately in the form of Set.
  15. Collection values(): This method returns all the Key-Values or entities in the Map separately in the form of Set.
  16. boolean containsKey(): This method returns true if specified Key is available in the Map otherwise it returns false.
  17. boolean containsValue(V obj): This method returns true if specified Value is available in the Map otherwise it returns false.
HashMap Collection in Java:

HashMap is the implementation class of Map interface which is used to store a group of objects in the form of Key-Value pairs where Keys cannot be duplicated but Values can be duplicated. HashMap internally follows the hashtable data structure.

HashMap is not a synchronized class. HashMap supports only one null value for Key Objects but we can store multiple null values for Value Object. HashMap is called an unordered Map because it is not guaranteed for the insertion order of elements.

Creating a HashMap
Syntax : HashMap<Key, Value> numbers = new HashMap<>(8, 0.6f); Here, Key – a unique identifier used to associate each element (value) in a map and Value – elements associated by keys in a map

HashMap Constructors

HashMap<K,V> hm = new HashMap<K,V>(); It is used to construct a default HashMap.
HashMap<K, V> hm = new HashMap<K, V>(int capacity); It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap<K, V> hm = new HashMap<K, V>(int capacity, float loadFactor); It is used to initialize both the capacity and load factor of the hash map by using its arguments.
HashMap<K, V> hm = new HashMap<K, V>(Map obj); It is used to initialize the hash map by using the elements of the given Map object obj.

Sample Program demonstrating HashMap Collection in Java
import java.util.*;
public class HashMapDemo {
 public static void main(String[] args) 
 {
  HashMap<Integer, String> hm = new HashMap<Integer, String>();
  hm.put(11, "Sachin");
  hm.put(37, "Dhoni");
  hm.put(25, "Kohli");
  hm.put(13, "Raina");
  hm.put(12, "Yuvraj");
  System.out.println(hm);
  System.out.println(hm.size());
  Set ks = hm.keySet();
  System.out.println(ks);
  Collection cv = hm.values();
  System.out.println(cv);
  Set entry = hm.entrySet();
  System.out.println(entry);
  System.out.println(hm.containsKey(12));
  System.out.println(hm.remove(25));
  System.out.println(hm);
 }
}

Output:

HashMap Collection in Java

HashMap Example with Complex Data type in Java:
import java.util.HashMap;
import java.util.Set;

public class HashMapDemo
{
    public static void main (String a[])
    {
        HashMap < Price, String > hm = new HashMap < Price, String > ();
        hm.put (new Price ("Banana", 20), "Banana");
        hm.put (new Price ("Apple", 40), "Apple");
        hm.put (new Price ("Orange", 30), "Orange");
        printMap (hm);
        Price key = new Price ("Banana", 20);
        System.out.println ("Does key available? " + hm.containsKey (key));
    }

    public static void printMap (HashMap < Price, String > map)
    {
        Set < Price > keys = map.keySet ();
        for (Price p:keys)
        {
         System.out.println (p + "==>" + map.get (p));
        }
    }
}

class Price
{
    private String item;
    private int price;

    public Price (String itm, int pr)
    {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode ()
    {
        System.out.println ("In hashcode");
        int hashcode = 0;
        hashcode = price * 20;
        hashcode += item.hashCode ();
        return hashcode;
    }

    public boolean equals (Object obj)
    {
        System.out.println ("In equals");
        if (obj instanceof Price)
        {
         Price pp = (Price) obj;
         return (pp.item.equals (this.item) && pp.price == this.price);
        }
        else
        {
         return false;
        }
    }

    public String getItem ()
    {
        return item;
    }
    public void setItem (String item)
    {
        this.item = item;
    }
    public int getPrice ()
    {
        return price;
    }
    public void setPrice (int price)
    {
        this.price = price;
    }

    public String toString ()
    {
        return "item: " + item + "  price: " + price;
    }
}

Output:

HashMap Example with Complex Data type in Java

Hashtable Collection in Java:

Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a given moment of time. The thread which works on Hashtable acquires a lock on it to make the other threads wait till its work gets completed. Hashtable doesn’t allow null keys and null values. Hashtable doesn’t guarantee any kind of order. It doesn’t maintain the mappings in any particular order.

Hashtable is the implementation class of Map interface which is also used to store a group of objects in the form of Key-Value pairs where Keys can’t be duplicated but values can be duplicated. Hashtable is exactly similar to HashMap but Hashtable is a synchronized class where HashMap is not a synchronized class.

Creating a Hashtable
Syntax : Hashtable<Integer, String> ht = new Hashtable<Integer, String>();

Hashtable Constructors

Hashtable(): It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity): It accepts an integer parameter and creates a hash table that contains a specified initial capacity.
Hashtable(int capacity, float loadFactor): It is used to create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map obj): It creates a new hash table with the same mappings as the given Map.

Sample Program to demonstrate Hashtable in Java
import java.util.*;
public class HashtableDemo {
 public static void main(String[] args) 
 {
  Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
  ht.put(11, "Sachin");
  ht.put(37, "Dhoni");
  ht.put(25, "Kohli");
  ht.put(13, "Raina");
  ht.put(12, "Yuvraj");
  System.out.println(ht);
  Enumeration e = ht.keys();
  while (e.hasMoreElements()) {
   System.out.println(e.nextElement());
  }
 }
}

Output:

Hashtable Collection in Java

HashTable Example with Complex Data type in Java:
import java.util.Hashtable;
public class HashtableDemo
{
    public static void main (String a[])
    {
        Hashtable < Employee, String > tm = new Hashtable < Employee, String > ();
        tm.put (new Employee (134, "Ram", 3000), "RAM");
        tm.put (new Employee (235, "John", 6000), "JOHN");
        tm.put (new Employee (876, "Crish", 2000), "CRISH");
        tm.put (new Employee (512, "Tom", 2400), "TOM");
        System.out.println ("Fecthing value by creating new key:");

        Employee e = new Employee (512, "Tom", 2400);
        System.out.println (e + " ==> " + tm.get (e));
    }
}

class Employee
{
    private String name;
    private int salary;
    private int id;

    public Employee (int id, String n, int s)
    {
        this.id = id;
        this.name = n;
        this.salary = s;
    }

    public String getName ()
    {
        return name;
    }
    public void setName (String name)
    {
        this.name = name;
    }
    public int getSalary ()
    {
        return salary;
    }
    public void setSalary (int salary)
    {
        this.salary = salary;
    }
    public String toString ()
    {
        return "Id: " + this.id + " -- Name: " + this.name + " -- Salary: " + this.salary;
    }

    public void setId (int id)
    {
        this.id = id;
    }

    public int getId ()
    {
        return id;
    } 

    @Override public int hashCode ()
    {
        System.out.println ("In hashcode");
        return this.getId ();
    }

    @Override public boolean equals (Object obj)
    {
        Employee e = null;
        if (obj instanceof Employee)
        {
         e = (Employee) obj;
        }
        System.out.println ("In equals");
        if (this.getId () == e.getId ())
        {
         return true;
        }
        else
        {
         return false;
        }
    }
}

Output:

HashTable Example with Complex Data type in Java

LinkedHashMap Collection in Java:

LinkedHashMap is the implementation class of Map interface which is also used to store a group of three objects in the form of Key-Value pairs where Keys cannot be duplicated but values can be duplicated. LinkedHashMap internally follows hashtable + doubly linked list structures.

The LinkedHashMap is not a synchronized class. LinkedHashMap supports only one null value for Key Objects but we can store multiple null values for Value Objects. LinkedHashMap is called an ordered Map because it is guaranteed for the insertion order of elements.

Creating a LinkedHashMap
Syntax : LinkedHashMap<Integer, String> hm = new LinkedHashMap <Integer, String>();

LinkedHashMap Constructors

LinkedHashMap(): It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity): It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor): It is used to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder): It is used to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map obj): It is used to initialize the LinkedHashMap with the elements from the given Map class obj.

Sample Program to demonstrate LinkedHashMap Collection in Java
import java.util.*;
public class LinkedHashMapDemo {
    public static void main(String args[]) {
         // HashMap Declaration
         LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>();

         //Adding elements to LinkedHashMap
         lhmap.put(22, "Abey");
         lhmap.put(33, "Dawn");
         lhmap.put(1, "Sherry");
         lhmap.put(2, "Karon");
         lhmap.put(100, "Jim");

         // Generating a Set of entries
         Set set = lhmap.entrySet();

         // Displaying elements of LinkedHashMap
         Iterator iterator = set.iterator();
         while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.print("Key is: "+ me.getKey() + 
                    "& Value is: "+me.getValue()+"\n");
         }
    }
}

Output:

LinkedHashMap Collection in Java

LinkedHashMap Example with Complex Data type in Java:
import java.util.LinkedHashMap;
import java.util.Set;

public class LinkedHashMapDemo
{
    public static void main (String a[])
    {
        LinkedHashMap < Price, String > hm = new LinkedHashMap < Price, String > ();
        hm.put (new Price ("Banana", 20), "Banana");
        hm.put (new Price ("Apple", 40), "Apple");
        hm.put (new Price ("Orange", 30), "Orange");
        printMap (hm);
        Price key = new Price ("Banana", 20);
        System.out.println ("Does key available? " + hm.containsKey (key));
    }

    public static void printMap (LinkedHashMap < Price, String > map)
    {
        Set < Price > keys = map.keySet ();
        for (Price p:keys)
        {
         System.out.println (p + "==>" + map.get (p));
        }
    }
}

class Price
{
    private String item;
    private int price;

    public Price (String itm, int pr)
    {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode ()
    {
        System.out.println ("In hashcode");
        int hashcode = 0;
        hashcode = price * 20;
        hashcode += item.hashCode ();
        return hashcode;
    }

    public boolean equals (Object obj)
    {
        System.out.println ("In equals");
        if (obj instanceof Price)
        {
         Price pp = (Price) obj;
         return (pp.item.equals (this.item) && pp.price == this.price);
        }
        else
        {
         return false;
        }
    }

    public String getItem ()
    {
        return item;
    }
    public void setItem (String item)
    {
        this.item = item;
    }
    public int getPrice ()
    {
        return price;
    }
    public void setPrice (int price)
    {
        this.price = price;
    }

    public String toString ()
    {
        return "item: " + item + "  price: " + price;
    }
}

Output:

LinkedHashMap Example with Complex Data type in Java

TreeMap Collection in Java:

TreeMap is the implementation class of Map interface which is also used to store a group of objects in the form of Key-Value pairs where Keys cannot be duplicated but values can be duplicated. TreeMap internally follows Tree Structure.

The TreeMap is not a synchronized class. TreeMap is called an unordered map because it is not guaranteed for the insertion order of elements, but all elements are stored in sorted order (by default ascending order based on keys).

TreeMap does not support null values for Key Objects but we can store multiple null values for Value Objects.

Creating a TreeMap
Syntax : TreeMap<Key, Value> numbers = new TreeMap<Key, Value>(); Here, Key – a unique identifier used to associate each element (value) in a map and Value – elements associated by keys in a map

TreeMap Constructors

TreeMap(): It is used to construct an empty treemap that will be sorted using the natural order of its key.
TreeMap(Comparator c): It is used to construct an empty tree-based map that will be sorted using the comparator c.
TreeMap(Map m): It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap sm): It is used to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Sample Program to demonstrate TreeMap Collection in Java
import java.util.*;  
class TreeMapDemo{  
    public static void main(String args[])
    {  
        TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
        map.put(100,"Amit");    
        map.put(102,"Ravi");    
        map.put(101,"Vijay");    
        map.put(103,"Rahul");    
        
        for(Map.Entry m:map.entrySet()){    
            System.out.println(m.getKey()+" "+m.getValue());    
        }    
    }  
}

Output:

Map Collections in Java

TreeMap Example with Complex Data type in Java:
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo 
{
    public static void main (String a[])
    {
        //By using name comparator (String comparison)
        TreeMap < Employee, String > tm = new TreeMap < Employee, String > (new MyNameComp ());
        tm.put (new Employee ("Ram", 3000), "RAM");
        tm.put (new Employee ("John", 6000), "JOHN");
        tm.put (new Employee ("Crish", 2000), "CRISH");
        tm.put (new Employee ("Tom", 2400), "TOM");
        Set < Employee > keys = tm.keySet ();
        for (Employee key:keys)
        {
         System.out.println (key + " ==> " + tm.get (key));
        }
        System.out.println ("===================================");
    
        //By using salary comparator (int comparison)
        TreeMap < Employee, String > trmap = new TreeMap < Employee, String > (new MySalaryComp ());
        trmap.put (new Employee ("Ram", 3000), "RAM");
        trmap.put (new Employee ("John", 6000), "JOHN");
        trmap.put (new Employee ("Crish", 2000), "CRISH");
        trmap.put (new Employee ("Tom", 2400), "TOM");
        Set < Employee > ks = trmap.keySet ();
        for (Employee key:ks)
        {
         System.out.println (key + " ==> " + trmap.get (key));
        }
    }
}

class MyNameComp implements Comparator < Employee >
{
    @Override public int compare (Employee e1, Employee e2)
    {
        return e1.getName ().compareTo (e2.getName ());
    }
}

class MySalaryComp implements Comparator < Employee >
{
    @Override public int compare (Employee e1, Employee e2)
    {
        if (e1.getSalary () > e2.getSalary ())
        {
         return 1;
        }
        else
        {
         return -1;
        }
    }
}

class Employee
{
    private String name;
    private int salary;

    public Employee (String n, int s)
    {
        this.name = n;
        this.salary = s;
    }

    public String getName ()
    {
        return name;
    }
    public void setName (String name)
    {
        this.name = name;
    }
    public int getSalary ()
    {
        return salary;
    }
    public void setSalary (int salary)
    {
        this.salary = salary;
    }
    public String toString ()
    {
        return "Name: " + this.name + "-- Salary: " + this.salary;
    }
}

Output:

TreeMap Example with Complex Data type in Java

In the next article, I am going to discuss Sorting Collections in Java with examples. Here, in this article, I try to explain Map Collections in Java with Examples and I hope you enjoy this Map Collections in Java with Examples article.

Leave a Reply

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