HashMap Java


HashMap Java Java MapViews 3077

HashMap Java stores the data in the form of key-value pairs where the key data should be unique. We can access the values based on the corresponding key data. HashMap is present in Java’s Collection framework and is part of java.util package. It works on the principle of the Hashing technique.

HashMap Java Hierarchy

The HashMap class in Java extends the Abstract class AbstractMap and implements the Map interface as shown below.

Java HashMap

HashMap structure and working principle

HashMap in Java works on the principle of hashing technique. In hashing, we use hash functions to link key and value in a HashMap. The HashMap stores the key-value pairs in the form of an array of nodes where each entry is considered as a bucket. A bucket is nothing but an element in an array. Each node has 3 values: Key, value, and link to the next node. When more than 1 node shares the same index, it represents a linked list. Every node is mapped to an index in the bucket which is calculated using hashcode().

HashMap in Java

HashMap Performance

Performance of HashMap Java depends on the below parameters:

  • Initial Capacity – It denotes how many buckets a HashMap can store when it is initialized. By default, it is 16 key-value pairs
  • Load Factor – It is the percentage of capacity that needs to be increased. By default, it is 0.75
  • Threshold – This is the product of load factor and capacity whose default value is 12 (16*0.75)
  • Rehashing – This is the process of doubling the capacity after it reaches a threshold value.

HashMap Java declaration

To use HashMap in Java, we need to import java.util.HashMap package. The syntax is as given below:

HashMap<KeyType,ValueType> map = new HashMap<>();

KeyType – It is the type of key data.Eg: String or Integer

ValueType – It is the type of value data. Eg: String or Integer

HashMap Features

Below are the features of HashMap in Java:

  • Stores values corresponding to each key
  • Contains only unique keys
  • Does not allow duplicate keys but can have duplicate values
  • It does not maintain any order which means the order in which data is inserted is not the same as the order in which it is retrieved.
  • It is non-synchronized

HashMap Java Class Constructors

HashMap supports 4 different constructors as you can see in the below table:

ConstructorDescription
HashMap()Initializes a default HashMap
HashMap(Mapm)Initializes the Hashmap with elements of Map m
HashMap(int capacity)Initializes the hashmap with the specified capacity integer value
HashMap(int capacity, float loadfactor)Initializes the hashmap with the specified capacity and loadfactor

HashMap Methods

HashMap in Java supports all the methods that belong to Map interface along with the methods mentioned in the below table

MethodDescriptionParameter
void clear()Removes all the mappings in this map which means map will be empty
Object clone()Returns a shallow copy of this HashMap instance. Key and values themselves are not cloned
Boolean containsKey(Object key)Returns true if there is a mapping value for the specified keykey - the key for which we need to retrieve the value
Boolean containsValue(Object value)Returns true if there is mapping of key for the specified valuevalue - the value for which specified key is mapped
Set<Entry> entrySet()Returns a set view of the mapping of the map
Boolean equals(Object o)Returns true if the object has the same mapping of the mapo - the object to be compared
Integer get(Object key)Returns the value of the specified key in the map. It returns null if there is no mappingkey - the key for which value mapping has to be retrieved
Integer getOrDefault(Object key, Integer defaultvalue)Returns the value of the specified key if mapped, else returns the defaultvalue if there is no mappingkey - the key for which we value has to be returned
defaultvalue - the default value to be returned when there is no mapping
int hashCode()Returns the hashcode value of the map
Boolean isEmpty()Returns true is the hashmap does not have any key-value pairs
Set keySet()Returns the set view of the keys present in the map
Integer put(String key, int value)Associates the key with value. If the key is already present, it replaces the old value with new valuekey - key for mapping
value - value for the specified key
void putAll(Map m)Associates all key - value mappings of m to the current mapm - the copies of the mapping to be added to the current map
Integer putIfAbsent(String key,Integer value)Associates the value if already not mapped to the key else returns the current valuekey - key for mapping
value - value to be associated
Integer remove(Object key)Removes the mapping for the specified key in the mapkey - the key in the map for which mapping has to be removed
Boolean remove(Object key, Object value)Removes the entry of the specified key only if it is mapped with the specified valuekey - key in map
value - value mapped to the key
Integer replace(String key, Integer value)Replaces the value of the specified key with the value only if it currently mapped with some valuekey - key in map
value - value to be replaced
Boolean replace(String key, integer oldvalue, Integer newvalue)Replaces the entry of the specified key with new value only if it already mapped with the specified oldvaluekey - key in the map
oldvalue - oldvalue mapped to key
newvalue - newvalue to be mapped to the key
int size()Returns the size of the map
String toString()Returns a string representation of the map
Collection values()Returns a collection view of values present in the map

HashMap Exceptions

It throws the below exceptions in Java:

  • ConcurrentModificationException
  • IllelgalMonitorStateException
  • NullPointerException
  • InterruptedException
  • IllegalArgumentException

Adding Elements to HashMap

As you can see in the below example, first we create a HashMap named ‘student’ with the key of String type and value of Integer type. We then add individual key-value pairs using the put method. You can notice in the output that the order in which the elements are retrieved is not the same as the order in which it was inserted.

Next, we create a second HashMap named ‘stu’ and then add 2 key-value pairs. This we then add to the ‘student’ map using the putAll method.

import java.util.HashMap;
public class HashMapAdd {

  public static void main(String[] args) {
    HashMap<String,Integer> student = new HashMap<>();
    student.put("Arthi", 100);
    student.put("Dev", 105);
    student.put("Banu",102);
    student.put("Rishi", 108);
    System.out.println("Elements in student map:");
    System.out.println(student);
    
    HashMap<String,Integer> stu = new HashMap<>();
    stu.put("Ravi",110);
    stu.put("Tejas", 112);
    System.out.println("Elements in stu map:");
    System.out.println(stu);
    
    student.putAll(stu);
    
    System.out.println("Elements in student map after invoking putAll method:");
    System.out.println(student);
  }

}
Elements in student map:
{Dev=105, Banu=102, Rishi=108, Arthi=100}
Elements in stu map:
{Ravi=110, Tejas=112}
Elements in student map after invoking putAll method:
{Dev=105, Ravi=110, Tejas=112, Banu=102, Rishi=108, Arthi=100}

Check if the map contains a specific key or value

We use containsKey method to check if a specific key is present in the map or not. In this case, Dev is present and hence it returns true and Ravi is not present and hence returns false.

Similarily, containsValue method checks if a specific value is present. Here, 102 is present but 110 is not present and hence returns false.

import java.util.HashMap;
public class HashMapAdd {

  public static void main(String[] args) {
    HashMap<String,Integer> student = new HashMap<>();
    student.put("Arthi", 100);
    student.put("Dev", 105);
    student.put("Banu",102);
    student.put("Rishi", 108);
    System.out.println("Elements in student map:");
    System.out.println(student);
    
    System.out.println(student.containsKey("Dev"));
    System.out.println(student.containsKey("Ravi"));
    
    System.out.println(student.containsValue(102));
    System.out.println(student.containsValue(110));
  }

}
Elements in student map:
{Dev=105, Banu=102, Rishi=108, Arthi=100}
true
false
true
false

Remove and Replace a key-value pair

Here, we create a hashmap in Java of Integer and String type to store languages. We replace the 2nd value with new data and replace the 3rd value if the specific key-value pair is present in the map using replace() method.

Then, we remove the 3rd element using the key and remove the 1st element using key-value using the remove() method.

import java.util.HashMap;
public class RemoveHashMap {

  public static void main(String[] args) {
    HashMap<Integer,String> lang = new HashMap<>();
    lang.put(1, "Java");
    lang.put(2, "C");
    lang.putIfAbsent(3, "C++");
    System.out.println(lang);
    
    lang.replace(2, "PHP");
    System.out.println(lang);
    
    lang.replace(3, "C++", "JavaScript");
    System.out.println(lang);
    
    lang.remove(3);
    System.out.println(lang);
    
    lang.remove(1, "Java");		
    System.out.println(lang);
    
    
  }

}
{1=Java, 2=C, 3=C++}
{1=Java, 2=PHP, 3=C++}
{1=Java, 2=PHP, 3=JavaScript}
{1=Java, 2=PHP}
{2=PHP}

Example of clear and empty methods

HashMap in Java uses the clear() method to clear the mapping of key-value pairs in the map and isEmpty method checks if the map is empty. The 1st output is false since mapping is present and 2nd output is true since the map does not have any key-value pairs after invoking the clear() method.

import java.util.HashMap;
public class RemoveHashMap {

  public static void main(String[] args) {
    HashMap<Integer,String> lang = new HashMap<>();
    lang.put(1, "Java");
    lang.put(2, "C");
    
    System.out.println(lang.isEmpty());
    lang.clear();
    
    System.out.println(lang.isEmpty());
    
  }

}
false
true

Iterating through HashMap elements using entrySet

To retrieve the individual key-value pairs of HashMap in Java, we can use the entrySet method of HashMap along with the Entry method of the Map interface using a for-each loop. The Entry method of the Map interface has built-in methods such as geyKey() to get the key and getValue() to get the corresponding value. We can use the size() method to get the size of the map.

import java.util.HashMap;
import java.util.Map;
public class IterateHashMap {

  public static void main(String[] args) {
    HashMap<String,String> cityState = new HashMap<>();
    cityState.put("Bangalore", "Karnataka");
    cityState.put("Chennai", "TamilNadu");
    cityState.put("Madurai", "TamilNadu");
    cityState.put("Mumbai", "Maharashtra");
    
    System.out.println("Size of map is : " + cityState.size());
    
    for(Map.Entry<String,String> m : cityState.entrySet())
    {
      System.out.println(m.getKey() + " : " + m.getValue());
    }

  }

}
Size of map is : 4
Chennai : TamilNadu
Madurai : TamilNadu
Mumbai : Maharashtra
Bangalore : Karnataka

Loop through elements using keySet() and values()

Another way to loop through Hashmap elements is by using the keySet() method. Using this, we can get a set of all keys separately as seen in the below example. To get all values separately, we can use the values() method and print them in for loop.

Using keySet, we can also print the key-value pairs by iterating in for loop by using get() method to get the corresponding values.

import java.util.HashMap;
import java.util.Map;
public class IterateHashMap {

  public static void main(String[] args) {
    HashMap<String,String> cityState = new HashMap<>();
    cityState.put("Bangalore", "Karnataka");
    cityState.put("Chennai", "TamilNadu");
    cityState.put("Madurai", "TamilNadu");
    cityState.put("Mumbai", "Maharashtra");
    
    System.out.println("Printing only keys:");
    for(String s : cityState.keySet())
    {
      System.out.println(s);
    }
    System.out.println();
    System.out.println("Printing only values: ");
    for(String c : cityState.values())
    {
      System.out.println(c);
    }
    System.out.println();
    System.out.println("Printing both key-value pairs:");
    for(String v : cityState.keySet())
    {
      System.out.println("Key: " + v + " | value: " + cityState.get(v));
    }
  }

}
Printing only keys:
Chennai
Madurai
Mumbai
Bangalore

Printing only values: 
TamilNadu
TamilNadu
Maharashtra
Karnataka

Printing both key-value pairs:
Key: Chennai | value: TamilNadu
Key: Madurai | value: TamilNadu
Key: Mumbai | value: Maharashtra
Key: Bangalore | value: Karnataka

Conclusion

In this tutorial, you have learned about HashMap Java and its different methods along with various examples.

Reference

Translate ยป