×

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one null key but many null values. It contains unique keys. It maintains no order. The initial capacity is 16, and the load factor is 0.75f. It can have multiple duplicate values.

Structure of HashMap

HashMap consist of the array of node and node is the class which contains 4 fields:
  1. Int Hash.
  2. K key.
  3. V value.
  4. Node next.

Declaration of HashMap

It uses the java.util. HashMap class. The declaration of HashMap is:
HashMap<String, String> hm= new HashMap<String, String> ();
hm -> it holds the reference of the objects.

Constructors in HashMap:

  • HashMap (): This is the default constructor with initial capacity is 16, and the load factor is 0.75f.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hma.put(1, "C");
hma.put(2, "C++");
hma.put(3, "Java");
System.out.println("Values of hma:" + hma); 
Output:
Values of hma :{ 1=C, 2=C++, 3=Java}} }
  • HashMap (int capacity): It is used to create the HashMap with specified capacity, and load factor is 0.75.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma= new HashMap<Integer, String> (3);
hma.put(1, "C");
hma.put(2, "C++");
hma.put(3, "Java");
System.out.println("Values of hma:" + hma); 
} }
Output:
Values of hma: {1=C, 2=C++, 3=Java}
  • HashMap (int capacity, float load factor): It is used to create the HashMap with specified capacity and load factor.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> (3,0.5f);
hma.put(1, "C");
hma.put(2, "C++");
hma.put(3, "Java");
System.out.println("Values of hma:" + hma); 
} }
Output:
Values of hma: {1=C, 2=C++, 3=Java}
  • HashMap (Map map): It is used to create the HashMap by using the map object.
Example:
import java.util.*;
public class HashMapExample {
public static void main(String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>(3, 0.5f);
hm.put(1, "C");
hm.put(2, "C++");
hm.put(3, "Java");
System.out.println("Values of hm:” + hm);
HashMap<Integer, String> language = new HashMap<Integer, String>(hm);
System.out.println("Values of language:" + language);
}}
Output:
Values of hm :{ 1=C, 2=C++, 3=Java}
Values of language :{ 1=C, 2=C++, 3=Java}

Time Complexity of HashMap:

The time complexity of HashMap operations is to provide Constant time. Iteration depends on the capacity of HashMap and the numbers of key-value pairs. It is directly proportional to Capacity + Size.

Methods of HashMap:

  1. clear (): It is used to remove all mapping from the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main(String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hm.put(1, "C");
hm.put(2, "C++");
hm.put(3, "Java");
System.out.println("Values of hm:" + hm);
hm.clear();
System.out.println("After clear the map:"+ hm);
}}
Output:
Values of hm: {1=C, 2=C++, 3=Java}
After clear the map :{}
  1. get (Object key): It is used to get the value of a particular key from the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main(String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>();
hma.put(1, "C");
hma.put(2, "C++");
hma.put(3, "Java");
System.out.println("Values of hma: " + hma);
System.out.println("The value in the map: "+ hma.get(3));
} }
Output:
Values of hma: {1=C, 2=C++, 3=Java}
The value in the map: Java
  1. put(object K, object V): It is used to insert the value of the specified key in the Map.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
hma.put (4,"Python");
System.out.println ("The value is:"+hma);
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
The value is: {1=C, 2=C++, 3=Java, 4=Python}
  1. containsKey(Object K): It returns true if the specified key is present on the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main(String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>();
hma.put(1, "C");
hma.put(2, "C++");
hma.put(3, "Java");
System.out.println("Values of hma: " + hma);
System.out.println("Is map contains the key: "+hma.containsKey (2));
System.out.println("Is map contains the key: "+hma.containsKey (8));
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
Is map contains the key: true
Is map contains the key: false
  1. containsValue (object V): It returns true if the specified value is present on the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
System.out.println ("Is map contains the value: "+hma.containsValue ("Python"));
System.out.println ("Is map contains the value: "+hma.containsValue ("C++"));
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
Is map contains the value: false
Is map contains the value: true
  1. clone (): This is used to return the same copy of the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
hma.clone ();
System.out.println (“Clone map:”+hma);
} }
Output:
Values of hma: {1=C, 2=C++, 3=Java}
Clone map: {1=C, 2=C++, 3=Java}
  1. isEmpty (): It is used to return true if the map is empty otherwise false.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
System.out.println ("Is map empty: "+hma.isEmpty ());
hma.clear ();
System.out.println ("Is map empty: "+hma.isEmpty ());
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
Is map empty: false
Is map empty: true
  1. size (): This method is used to return the size of the map.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
System.out.println ("Size of map: "+hma.size ());
hma.clear ();
System.out.println ("Size of map: "+hma.size ());
} }
Output:
Values of hma: {1=C, 2=C++, 3=Java}
Size of map: 3
Size of map: 0
  1. putAll (Map m): This is used to copy all elements from the map to another map.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String>();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
HashMap<Integer, String> hm1 = new HashMap<Integer, String> ();
hm1.putAll (hm);
System.out.println ("The new map: "+hm1);
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
The new map: {1=C, 2=C++, 3=Java}
  1. remove (object K): This is used to remove the value of the particular key.
Example:
import java.util.*;
public class HashMapExample {
public static void main (String [] args) {
HashMap<Integer, String> hma = new HashMap<Integer, String> ();
hma.put (1, "C");
hma.put (2, "C++");
hma.put (3, "Java");
System.out.println ("Values of hma: " + hma);
hma.remove (3);
System.out.println ("After removing: "+hma);
} }
Output:
Values of hm: {1=C, 2=C++, 3=Java}
After removing: {1=C, 2=C++}

Difference between HashMap and HashTable:

HashMap HashTable
1. Traversed by Iterator. 1. Traversed by Enumerator and Iterator.
2. Inherits AbstractMap Class. 2. Inherits Dictionary Class.
3. Hashmap permits one null key and multiple null values. 3. hashTable do not allow one null key and value.
4. HashMap is not synchronized. 4. HashTable is synchronized.
5. Performance is fast. 5. Performance is slow.
6. Complexity is O (1). 6. Complexity is O (1).
7. Not legacy and introduced in 1.2v. 7. Legacy and introduced in 1.0v.

Traverse through a HashMap:

HashMap internally uses the Hashing technique. There are three ways to traverse in HashMap:
  1. using iterator:
Example:
import java.util.*;
public class IteratorExample {
public static void main (String [] args) {
HashMap<String, Integer> hm = new HashMap<String, Integer> ();
hm.put ("TutorialandExample", 54);
hm.put ("A computer portal", 80);
hm.put ("For Students", 82);
System.out.println ("Created HashMap is: " + hm);
Iterator hmi= hm.entrySet ().iterator ();
System.out.println ("HashMap after adding :");
while (hmi.hasNext ()) {
Map.Entry m = (Map.Entry) hmi.next ();
int marks = ((int)m.getValue () + 10);
System.out.println (m.getKey () + “: “+ marks);
} } }
Output:
Created HashMap is: {For Students=82, A computer portal=80, TutorialandExample=54}
HashMap after adding bonus marks:
For Students: 92
A computer portal: 90
TutorialandExample: 64
  1. Using for-each loop:
Example:
import java.util.*;
public class ForEachExample {
public static void main (String [] args) {
HashMap<String, Integer> hm = new HashMap<String, Integer> ();
hm.put ("TutorialandExample", 54);
hm.put ("A computer portal", 80);
hm.put ("For Students", 82);
System.out.println ("Created HashMap is: " + hm);
for (Map.Entry m: hm.entrySet ()) {
String key = (String) m.getKey();
int value = ((int) m.getValue () + 10);
System.out.println (key + “: “+ value);
} } }
Output:
Created HashMap is: {For Students=82, A computer portal=80, TutorialandExample=54}
For Students: 92
A computer portal: 90
TutorialandExample: 64
  1. Using forEach () method:
Example:
import java.util.*;
public class ForEachExample {
public static void main (String [] args) {
HashMap<String, Integer> hm = new HashMap<String, Integer> ();
hm.put ("TutorialandExample", 54);
hm.put ("A computer portal", 80);
hm.put ("For Students", 82);
System.out.println ("Created HashMap is: " + hm);
System.out.println ("HashMap after adding: ");
forEach ((k, v) -> System.out.println (k + ": "+ (v + 10)));
} }
Output:
Created HashMap is: {For Students=82, A computer portal=80, TutorialandExample=54}
HashMap after adding:
For Students: 92
A computer portal: 90
TutorialandExample: 64

Related Topics

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.