Java HashMap
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java HashMap

Jeevadharshan

Java HashMap  

A HashMap is one of the most commonly used classes in the Java Collections Framework. It stores data as key-value pairs, where every unique key is associated with a single value. 
 
The HashMap class belongs to the java.util package and implements the Map interface. Unlike an ArrayList, which retrieves elements using an index, a HashMap retrieves values by using their corresponding keys. 
 
A HashMap is an excellent choice when you need fast data lookup, insertion, and deletion based on unique keys.

Why Use HashMap? 

Use a HashMap when you need to:
  • Store data as key-value pairs. 
  • Retrieve values quickly using a unique key. 
  • Prevent duplicate keys. 
  • Build lookup tables, dictionaries, or configuration settings. 
  • Associate one object with another, such as product IDs with product names.

Creating a HashMap 

To use a HashMap, first import the java.util.HashMap class and create an object by specifying the data types for its keys and values. 
 
Example 
 
The following program creates a HashMap that stores employee IDs and employee names. 
 
java id="hmap001" 
import java.util.HashMap; 
 
public class EmployeeMapExample { 
    public static void main(String[] args) { 
 
        HashMap<Integer, String> employees = new HashMap<>(); 
 
        employees.put(101, "Alice"); 
        employees.put(102, "Brian"); 
        employees.put(103, "Charles"); 
 
        System.out.println(employees); 
    } 

Output 

text id="hmout001" 
{101=Alice, 102=Brian, 103=Charles}  

Adding Items 

Use the put() method to insert new key-value pairs into a HashMap. If the specified key already exists, its old value is replaced with the new value. 
 
Example
 
java id="hmap002" 
import java.util.HashMap; 
 
public class ProductPriceExample { 
    public static void main(String[] args) { 
 
        HashMap<String, Double> products = new HashMap<>(); 
 
        products.put("Laptop", 64999.0); 
        products.put("Keyboard", 1499.0); 
        products.put("Mouse", 899.0); 
 
        // Updates the existing value 
        products.put("Mouse", 999.0); 
 
        System.out.println(products); 
    } 
}  

Output 

text id="hmout002" 
{Laptop=64999.0, Keyboard=1499.0, Mouse=999.0} 
 
Note: A HashMap does not allow duplicate keys. Adding the same key again replaces the 
previous value.   

Accessing an Item 

Use the get() method to retrieve the value associated with a specific key. 
 
Example 
 
java id="hmap003" 
import java.util.HashMap; 
 
public class AccessExample { 
    public static void main(String[] args) { 
 
        HashMap<String, String> courses = new HashMap<>(); 
 
        courses.put("J101", "Java Basics"); 
        courses.put("P201", "Python Programming"); 
 
        System.out.println(courses.get("J101")); 
    } 

Output 

text id="hmout003" 
Java Basics

Removing Items 

Use the remove() method to delete a key-value pair. 
 
Example 
 
java id="hmap004" 
import java.util.HashMap; 
 
public class RemoveExample { 
    public static void main(String[] args) { 
 
        HashMap<String, String> browsers = new HashMap<>(); 
 
        browsers.put("C", "Chrome"); 
        browsers.put("F", "Firefox"); 
        browsers.put("E", "Edge"); 
 
        browsers.remove("F"); 
 
        System.out.println(browsers); 
    } 
 
To remove all entries from the map, use the clear() method. 
 
browsers.clear(); 

Finding the Size of a HashMap 

Use the size() method to determine how many key-value pairs are stored in a HashMap. 
 
Example 
 
java id="hmap005" 
import java.util.HashMap; 
 
public class SizeExample { 
    public static void main(String[] args) { 
 
        HashMap<Integer, String> students = new HashMap<>(); 
 
        students.put(1, "Emma"); 
        students.put(2, "Liam"); 
        students.put(3, "Sophia"); 
 
        System.out.println("Total Students: " + students.size()); 
    } 

Output 

text id="hmout005" 
Total Students: 3 
 
Note: Only unique keys are counted. Updating an existing key does not increase the size of the map.  

Looping Through a HashMap 

Java provides several ways to iterate through a HashMap. 

Print All Keys 

Use the keySet() method. 
 
java id="hmap006" 
for (String key : books.keySet()) { 
    System.out.println(key); 

 Print All Values 

Use the values() method. 
 
java id="hmap007" 
for (String value : books.values()) { 
    System.out.println(value); 
}  

Print Keys and Values 

Use the entrySet() method, which is the most efficient way to iterate through a HashMap. 
 
java id="hmap008" 
import java.util.HashMap; 
import java.util.Map; 
 
public class EntrySetExample { 
    public static void main(String[] args) { 
 
        HashMap<Integer, String> departments = new HashMap<>(); 
 
        departments.put(10, "Sales"); 
        departments.put(20, "Marketing"); 
        departments.put(30, "Finance"); 
 
        for (Map.Entry<Integer, String> entry : departments.entrySet()) { 
            System.out.println(entry.getKey() + " -> " + entry.getValue()); 
        } 
    } 
}  

Output 

text id="hmout008" 
 
10 -> Sales 
20 -> Marketing 
30 -> Finance

Using Different Data Types 

The keys and values in a HashMap must be objects. Primitive data types such as int, double, and char cannot be used directly. 
 
Instead, use their wrapper classes:

Table

Primitive Type  Wrapper Class 
int Integer 
double Double 
char Character 
boolean Boolean 
long Long 
float Float

Example 
 
java id="hmap009" 
import java.util.HashMap; 
 
public class StudentMarks { 
    public static void main(String[] args) { 
 
        HashMap<String, Integer> marks = new HashMap<>(); 
 
        marks.put("David", 88); 
        marks.put("Olivia", 94); 
        marks.put("Noah", 81); 
 
        System.out.println(marks); 
    } 
}  

When Order Matters 

A HashMap does not guarantee the order of its elements. If you need entries to remain in the order they were inserted, use a LinkedHashMap. If you need entries sorted by their keys, use a TreeMap. 

Using the `var` Keyword (Java 10+) 

Starting with Java 10, you can use the `var` keyword for local variable type inference. 
 
Without `var` 
 
HashMap<String, Integer> inventory = new HashMap<>(); 
 
With `var` 
 
var inventory = new HashMap<String, Integer>(); 
 
Although var reduces code length, many developers prefer explicit types because they improve code readability.  

Declaring a Map Using the Interface 

A common Java best practice is to declare variables using the Map interface rather than the HashMap class. 
 
Example 
 
import java.util.Map; 
import java.util.HashMap; 
 
public class MapExample { 
    public static void main(String[] args) { 
 
        Map<String, String> languages = new HashMap<>(); 
 
        languages.put("JS", "JavaScript"); 
        languages.put("PY", "Python"); 
        languages.put("JV", "Java"); 
 
        System.out.println(languages); 
    } 
 
Using the interface instead of the implementation makes your code more flexible and easier to maintain. You can replace `HashMap` with another implementation, such as TreeMap or LinkedHashMap,without changing the rest of your code.

Our website uses cookies to enhance your experience. Learn More
Accept !