Java HashMap

Introduction

HashMap in Java is part of the Java Collections Framework and implements the Map interface. It is a hash table-based implementation that provides the ability to store and retrieve key-value pairs. HashMap allows one null key and multiple null values and offers constant-time performance for basic operations like get and put, assuming the hash function disperses the elements properly among the buckets.

Table of Contents

  1. What is HashMap?
  2. Key Points About HashMap
  3. Creating a HashMap and Adding Elements
  4. Accessing Elements in a HashMap
  5. Modifying Elements in a HashMap
  6. Removing Elements from a HashMap
  7. Iterating Over a HashMap
  8. Searching for Elements in a HashMap
  9. HashMap of User-Defined Objects
  10. Common HashMap Methods
  11. Conclusion

1. What is HashMap?

A HashMap is a collection that stores key-value pairs. It uses a hash table to store the map, which allows for fast retrieval of elements. HashMap does not maintain any order of the elements, neither the insertion order nor any sorted order.

2. Key Points About HashMap

  • Key-Value Pairs: Stores data in key-value pairs.
  • Null Keys and Values: Allows one null key and multiple null values.
  • No Order: Does not maintain any specific order of elements.
  • Hashing: Uses hash table for storage.
  • Performance: Provides constant-time performance for basic operations like put and get, assuming the hash function disperses the elements properly among the buckets.
  • Non-Synchronized: Not thread-safe by default.

3. Creating a HashMap and Adding Elements

To create a HashMap, you can use the HashMap constructor. You can then use methods such as put to add key-value pairs to the map.

Example:

In this example, we create a HashMap of strings and integers and add a few key-value pairs to it.

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

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();

        // Adding elements to the HashMap
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);
        map.put(null, 4); // Null key
        map.put("Date", null); // Null value

        // Displaying the HashMap
        System.out.println("HashMap: " + map);
    }
}

Output:

HashMap: {null=4, Apple=1, Banana=2, Cherry=3, Date=null}

4. Accessing Elements in a HashMap

You can access elements in a HashMap using the get method by providing the key.

Example:

In this example, we demonstrate how to access elements in a HashMap.

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

public class AccessHashMap {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        // Accessing elements
        System.out.println("Value for 'Banana': " + map.get("Banana"));
        System.out.println("Value for 'Mango': " + map.get("Mango")); // Key not present
    }
}

Output:

Value for 'Banana': 2
Value for 'Mango': null

5. Modifying Elements in a HashMap

You can modify elements in a HashMap using the put method, which will replace the value for the given key if it already exists.

Example:

In this example, we demonstrate how to modify elements in a HashMap.

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

public class ModifyHashMap {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        // Modifying an element
        map.put("Banana", 4); // Updating value for key "Banana"

        // Displaying the updated HashMap
        System.out.println("Updated HashMap: " + map);
    }
}

Output:

Updated HashMap: {Apple=1, Banana=4, Cherry=3}

6. Removing Elements from a HashMap

You can remove elements from a HashMap using methods such as remove and clear.

Example:

In this example, we demonstrate how to remove elements from a HashMap.

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

public class RemoveHashMap {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        // Removing an element
        map.remove("Banana");

        // Displaying the HashMap after removal
        System.out.println("HashMap after removal: " + map);

        // Clearing the HashMap
        map.clear();
        System.out.println("HashMap after clearing: " + map);
    }
}

Output:

HashMap after removal: {Apple=1, Cherry=3}
HashMap after clearing: {}

7. Iterating Over a HashMap

You can iterate over a HashMap using various methods such as a simple for-each loop, entrySet, and keySet.

Example:

In this example, we demonstrate different ways to iterate over a HashMap.

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

public class IterateHashMap {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        // Using for-each loop with entrySet
        System.out.println("Using for-each loop with entrySet:");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Using for-each loop with keySet
        System.out.println("Using for-each loop with keySet:");
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }

        // Using forEach method (Java 8 and later)
        System.out.println("Using forEach method:");
        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Output:

Using for-each loop with entrySet:
Apple: 1
Banana: 2
Cherry: 3
Using for-each loop with keySet:
Apple: 1
Banana: 2
Cherry: 3
Using forEach method:
Apple: 1
Banana: 2
Cherry: 3

8. Searching for Elements in a HashMap

You can search for elements in a HashMap using methods such as containsKey and containsValue.

Example:

In this example, we demonstrate how to check if a HashMap contains a specific key or value.

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

public class SearchHashMap {
    public static void main(String[] args) {
        // Creating a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        // Check if the HashMap contains a specific key
        System.out.println("Does the HashMap contain 'Banana'? " + map.containsKey("Banana"));
        System.out.println("Does the HashMap contain 'Mango'? " + map.containsKey("Mango"));

        // Check if the HashMap contains a specific value
        System.out.println("Does the HashMap contain value 3? " + map.containsValue(3));
        System.out.println("Does the HashMap contain value 4? " + map.containsValue(4));
    }
}

Output:

Does the HashMap contain 'Banana'? true
Does the HashMap contain 'Mango'? false
Does the HashMap contain value 3? true
Does the HashMap contain value 4? false

9. HashMap of User-Defined Objects

You can use HashMap to store user-defined objects as keys or values. This involves creating a class for the objects you want to store and ensuring that the equals and hashCode methods are properly overridden for keys.

Example:

In this example, we create a Person class and then create a HashMap to store Person objects as keys.

import java.util.HashMap;
import java.util.Map
import java.util.Objects;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class UserDefinedObjectHashMap {
    public static void main(String[] args) {
        // Creating a HashMap with Person objects as keys
        Map<Person, String> map = new HashMap<>();
        map.put(new Person("Alice", 30), "Engineer");
        map.put(new Person("Bob", 25), "Designer");
        map.put(new Person("Charlie", 35), "Manager");

        // Displaying the HashMap
        for (Map.Entry<Person, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

Person{name='Alice', age=30}: Engineer
Person{name='Bob', age=25}: Designer
Person{name='Charlie', age=35}: Manager

10. All HashMap Class Methods

11. Conclusion

HashMap is a versatile and powerful data structure in Java that provides a way to store key-value pairs with fast access and retrieval. It allows one null key and multiple null values and offers constant-time performance for basic operations. Understanding how to create, manipulate, and iterate over HashMap can help you effectively manage collections of key-value pairs in your Java applications. With methods for adding, removing, accessing, and searching elements, HashMap offers a comprehensive solution for managing maps of data.

By using HashMap, you can ensure efficient data storage and retrieval in scenarios where order does not matter, and duplicate keys are not allowed. It is a fundamental data structure in Java, and mastering its usage will greatly enhance your programming skills.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top