Java HashMap

Java HashMap

HashMap Class In Java
  • Java HashMap class implements the Map interface by using a hashtable.
  •  It inherits AbstractMap class and implements the Map interface.
  • The important points about the Java HashMap class are given as follows -
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • The HashMap class extends AbstractMap and implements the Map interface. 
  • It uses a hash table to store the map.
  • This allows the execution time of get( ) and put( ) to remain constant even for large sets.
  •  It maintains no order.
  • A HashMap contains values based on the key.
  • HashMap is a generic class that has this declaration -
class HashMap<M,N>
Here, M specifies the type of keys, and N specifies the type of values.
Example -
package javaLearnings;

import java.util.*;

// Demonstrate LinkedList.
public class Main {

  public static void main(String args[]) {
// Create a hash map.
      HashMap hm = new HashMap();
// Put elements to the map
      hm.put("Mukul Agrawal", new Double(4737.23));
      hm.put("Technical content writter ", new Double(234.545));
      hm.put("Web desinging house", new Double(2342.23));
      hm.put("Online Promotion House", new Double(33.123));
      hm.put("Hello world", new Double(-435.32));
// Get a set of the entries.
      Set> set = hm.entrySet();
// Display the set.
      for(Map.Entry me : set) {
          System.out.print(me.getKey() + ": ");
// Deposit 1000 into John Doe's account.
      double balance = hm.get("Mukul Agrawal");
      hm.put("Mukul agrawal", balance + 1000);
      System.out.println("Mukul agrawals new balance: " +
              hm.get("Mukul agrawal"));


Output -
Methods - 
  • We can find the HashMap size using size() method, ex - hm.size().
  • As we have seen we can add elements using put() method.
  • To remove all items clear() is used 
  • To remove a particular item remove() is used.