HashMap in Java

  • The HashMap let you store data as key or value pairs, where both the key and the value are objects.
  • The HashMap class extends AbstractMap and implements Map interface.
  • The HashMap uses hash table for internal storage.
  • The HashMap permits null value and null key.
  • HashMap is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
  • The two most important HashMap's methods are:
get(Object Key) -  returns the value associated with specified key in this hash map, or null if there is no value for this key.

put(Object Ket, Object Value) - associates the specified value with the specified key in this map.

The following table demonstrates the constructors of HashMap and corresponding methods.

Constructor
Meaning
HashMap()
Constructs a new empty map object.
HashMap (Map m)
Constructs a new map with the given map.
HashMap (int Capacity)
Constructs a new map with the given capacity.
HashMap (int Capacity, float loadfactor)
Constructs a new map with the given capacity and the given load factor.

The following program shows a simple use of HashMap.

Example:

/**
From SimpleHashMap.java
*/

import java.util.HashMap;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleHashMap
{
  public static void main(String args[])
  {
      HashMap<String,Float> hmap = new HashMap<String,Float>();
      hmap.put("Apple", new Float(88.91));
      hmap.put("Grape", new Float(78.45));
      hmap.put("Banana", new Float(92.61));
      hmap.put("Mango", new Float(95.11));
      hmap.put("Orange", new Float(82.54));
      hmap.put("Pinapple", new Float(73.41));

      System.out.println("The HashMap elements are"+"\n"+hmap);
   
  }
}

Output:
The HashMap elements are
{Pinapple=73.41, Mango=95.11, Apple=88.91, Orange=82.54, Banana=92.61, Grape=78.45}

The following program shows use of HashMap with Iterator and Map Interface.

Example:

/**
From HashmapwithIterator.java
*/

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

/**
 *
 * @author JavaHotSpot
 */
public class HashmapwithIterator
{
      public static void main(String args[])
  {
      HashMap<String,Float> hmap = new HashMap<String,Float>();

      hmap.put("Apple", new Float(88.91));
      hmap.put("Grape", new Float(78.45));
      hmap.put("Banana", new Float(92.61));
      hmap.put("Mango", new Float(95.11));
      hmap.put("Orange", new Float(82.54));
      hmap.put("Pinapple", new Float(73.41));
      System.out.println("The HashMap elements are");
      Set set = hmap.entrySet();
      Iterator it = set.iterator();
      while(it.hasNext())
      {
          Map.Entry mapent = (Map.Entry)it.next();
          System.out.println(mapent.getKey()+"="+mapent.getValue());
      }
  }
}

Output:
The HashMap elements are
Pinapple=73.41
Mango=95.11
Apple=88.91
Orange=82.54
Banana=92.61
Grape=78.45