Java HashMap

The ArrayList is used to store set of values in an array and can be accessed using the index position. But, in HashMap we can use key/value pair to store the elements. We then use the key to retrieve the value.

In this tutorial we shall learn to

  • Create a HashMap
  • Adding element to the HashMap
  • Access element in HashMap
  • Change element value in HashMap
  • Remove element in HashMap

Create a HashMap

We need to import java.util.HashMap package in order to use HashMap. After import the package we can create HashMap using the following syntax.

Syntax to create a HashMap

HashMap<K, V> numbers = new HashMap<>();

Here, K represents key data type and V represents the value data type.

Example to create a HashMap

HashMap<String, Integer> weekDays = new HashMap<>();

In the above example, the type of the key is String and type of the value is Integer.

Add element to the HashMap

We use put() method to add an element to the HashMap. It takes two parameters. First parameter is the key and second parameter is the value for the key.

Example for adding element to HashMap

import java.util.HashMap;
    
    class Main {
      public static void main(String[] args) {
    
        // create a hashmap
        HashMap<String, Integer> weekDays = new HashMap<>();
    
        // add element using put() method
        weekDays.put("Sunday", 1);
        weekDays.put("Monday", 2);
        weekDays.put("Tuesday", 3);
        weekDays.put("Wednesday", 4);
        weekDays.put("Thursday", 5);
        weekDays.put("Friday", 6);
        weekDays.put("Saturday", 7);
        System.out.println("Values of Hashmap are " + weekDays);
      }
    }

Output

Values of Hashmap are {Monday=2, Thursday=5, Friday=6, Sunday=1, Wednesday=4, Tuesday=3, Saturday=7}

In the above example, we created a HashMap variable weekDays, and using put() method we add data to it and finally print the values of weekDays HashMap.

Access element in HashMap

In order to access the element in the HashMap we use get() method.
The get() method takes the key as parameter and return the value of the key if available. If the key is not present then it will return null.

Example to get values in HashMap

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<Integer, String> programmingLanguages = new HashMap<>();
    programmingLanguages.put(1, "C Programming");
    programmingLanguages.put(2, "C++");
    programmingLanguages.put(3, "Java");
    programmingLanguages.put(4, "C#");

    String value_1 = programmingLanguages.get(1);
    String value_2 = programmingLanguages.get(10);
    System.out.println("Value with key 1 is "+ value_1);
    System.out.println("Value with key 10 is "+ value_2);
  }
}

Output

Value with key 1 is C Programming
Value with key 10 is null

In the above program, we have created programmingLanguages variable of type HashMap add few key/value pairs to it.

Then, we try to get the values using get() method. The key 1 is present in the HashMap, so it returns C Programming as its value. The key 10 is not present in the HashMap, so it returns null.

Change element value in HashMap

The replace() method of HashMap class is used to replace the value of the key in the hashmap variable.

Example for changing value in HashMap

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<Integer, String> programmingLanguages = new HashMap<>();
    programmingLanguages.put(1, "C Programming");
    programmingLanguages.put(2, "C++");
    programmingLanguages.put(3, "Java");
    programmingLanguages.put(4, "C#");
    
    
    System.out.println("Before: Value with key 1 is "+ programmingLanguages.get(1));
    
    programmingLanguages.replace(1,"C");
    System.out.println("After: Value with key 1 is "+ programmingLanguages.get(1));

  }
}

Output

Before: Value with key 1 is C Programming
After: Value with key 1 is C

In the above program, we have updated the existing program by using replace() method to replace the value with key 1.

Remove element in HashMap

The remove() method of the HashMap class is used to remove the element in the HashMap.

The remove() method take the key as its parameter.

Example for removing element in HashMap

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<Integer, String> programmingLanguages = new HashMap<>();
    programmingLanguages.put(1, "C Programming");
    programmingLanguages.put(2, "C++");
    programmingLanguages.put(3, "Java");
    programmingLanguages.put(4, "C#");
    
    
    System.out.println("Value with key 1 is "+ programmingLanguages.get(1));
    
    programmingLanguages.remove(1);
    System.out.println("After removing: Value with key 1 is "+ programmingLanguages.get(1));

  }
}

Output

Value with key 1 is C Programming
After removing: Value with key 1 is null

In the above program, we have used remove() method to remove the element with the 1 and then try to get the value with key 1 which returns null.

Looping through HashMap

We can loop through the elements of HashMap using for-each loop and get each elements available in it.

Example to loop through HashMap

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
  public static void main(String[] args) {

    HashMap<Integer, String> programmingLanguages = new HashMap<>();
    programmingLanguages.put(1, "C Programming");
    programmingLanguages.put(2, "C++");
    programmingLanguages.put(3, "Java");
    programmingLanguages.put(4, "C#");
    
    
    for (Entry<Integer, String> entry : programmingLanguages.entrySet()) {
      System.out.println(entry.getKey()+"-"+entry.getValue());
    }

  }
}

Output

1-C Programming
2-C++
3-Java
4-C#

In the above program, we have used the used Entry which is available in the java.util.Map.Entry package.

To loop through the haspmap we use the entrySet() method in for-each loop and get each element as an Entry using

for(Entry<Integer, String> entry : programmingLanguages.entrySet())		        
{
....
}

To get the key from the Entry we use getKey() method and to get the value in the Entry we use getValue() method.

Other important methods available in HashMap

Method Description
clear() removes all the entry in HashMap
size() gets the size of the HashMap
containsKey() checks whether the key is present in the HashMap and returns true or false
containsValue() checks whether the value is present in the HashMap and returns true or false
isEmpty() check whether the HashMap is empty or not and returns true or false

Example program for HashMap using different methods

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
  public static void main(String[] args) {

    HashMap<Integer, String> programmingLanguages = new HashMap<>();
    programmingLanguages.put(1, "C Programming");
    programmingLanguages.put(2, "C++");
    programmingLanguages.put(3, "Java");
    programmingLanguages.put(4, "C#");
    
    System.out.println("Size: "+ programmingLanguages.size());
    System.out.println("Entry Available: "+ !programmingLanguages.isEmpty());
    
    System.out.println("Available Keys:");
    for(int key: programmingLanguages.keySet()){
        System.out.print(key+" ");
    }
    System.out.println();
    System.out.println("Available Values:");
    for(String value: programmingLanguages.values()){
        System.out.print(value+" ");
    }
  }
}

Output

Entry Available: true
Available Keys:
1 2 3 4 
Available Values:
C Programming C++ Java C#

Most Read