Java HashMap Methods Tutorial with Examples

HashMap is a part of the Java Collections Framework and provides the implementation of the Map interface. It is used to store key-value pairs and allows for fast retrieval based on the key. This tutorial will cover all methods of HashMap with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. HashMap Methods
    • put()
    • putAll()
    • get()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • containsKey()
    • containsValue()
    • keySet()
    • values()
    • entrySet()
    • forEach()
    • replace()
    • compute()
    • computeIfAbsent()
    • computeIfPresent()
    • merge()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

A HashMap in Java is a part of the Java Collections Framework and provides a way to manage key-value pairs. It is found in the java.util package and is backed by a hash table, which allows for fast access to elements based on keys.

2. Key Points

  • HashMap allows null values and the null key.
  • It does not maintain any order of elements.
  • It is not synchronized.
  • It provides constant-time performance for basic operations like put, get, and remove.

3. HashMap Methods

3.1. put()

The put() method is used to insert key-value pairs into the HashMap.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.2. putAll()

The putAll() method adds all key-value pairs from another map to the HashMap.

Example:

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

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);

        Map<String, Integer> moreFruits = new HashMap<>();
        moreFruits.put("Mango", 20);
        moreFruits.put("Orange", 40);

        fruits.putAll(moreFruits);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20, Orange=40}

3.3. get()

The get() method retrieves the value associated with the specified key.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.get("Banana")); // 30
    }
}

Output:

30

3.4. remove()

The remove() method removes the key-value pair associated with the specified key.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.remove("Banana");
        System.out.println(fruits); // {Apple=50, Mango=20}
    }
}

Output:

{Apple=50, Mango=20}

3.5. clear()

The clear() method removes all key-value pairs from the HashMap.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.clear();
        System.out.println(fruits); // {}
    }
}

Output:

{}

3.6. size()

The size() method returns the number of key-value pairs in the HashMap.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.size()); // 3
    }
}

Output:

3

3.7. isEmpty()

The isEmpty() method checks if the HashMap is empty.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        System.out.println(fruits.isEmpty()); // true
        fruits.put("Apple", 50);
        System.out.println(fruits.isEmpty()); // false
    }
}

Output:

true
false

3.8. containsKey()

The containsKey() method checks if the HashMap contains a specified key.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsKey("Banana")); // true
        System.out.println(fruits.containsKey("Mango")); // false
    }
}

Output:

true
false

3.9. containsValue()

The containsValue() method checks if the HashMap contains a specified value.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsValue(30)); // true
        System.out.println(fruits.containsValue(20)); // false
    }
}

Output:

true
false

3.10. keySet()

The keySet() method returns a set view of the keys contained in the HashMap.

Example:

import java.util.HashMap;
import java.util.Set;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Set<String> keys = fruits.keySet();
        System.out.println(keys); // [Apple, Banana, Mango]
    }
}

Output:

[Apple, Banana, Mango]

3.11. values()

The values() method returns a collection view of the values contained in the HashMap.

Example:

import java.util.HashMap;
import java.util.Collection;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Collection<Integer> values = fruits.values();
        System.out.println(values); // [50, 30, 20]
    }
}

Output:

[50, 30, 20]

3.12. entrySet()

The entrySet() method returns a set view of the mappings contained in the HashMap.

Example:

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

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Set<Entry<String, Integer>> entries = fruits.entrySet();
        for (Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.13. forEach()

The forEach() method performs the given action for each

entry in the HashMap.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.forEach((key, value) -> System.out.println(key + " = " + value));
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.14. replace()

The replace() method replaces the entry for the specified key only if it is currently mapped to some value.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.replace("Banana", 40);
        System.out.println(fruits); // {Apple=50, Banana=40, Mango=20}
    }
}

Output:

{Apple=50, Banana=40, Mango=20}

3.15. compute()

The compute() method computes a new mapping for the specified key and its current mapped value (or null if there is no current mapping).

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.compute("Banana", (key, value) -> (value == null) ? 40 : value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40}
    }
}

Output:

{Apple=50, Banana=40}

3.16. computeIfAbsent()

The computeIfAbsent() method computes a mapping for the specified key if it is not already present.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfAbsent("Mango", key -> 20);
        System.out.println(fruits); // {Apple=50, Banana=30, Mango=20}
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.17. computeIfPresent()

The computeIfPresent() method computes a new mapping for the specified key if it is currently present.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfPresent("Banana", (key, value) -> value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40}
    }
}

Output:

{Apple=50, Banana=40}

3.18. merge()

The merge() method merges the specified value with the existing value associated with the specified key.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.merge("Banana", 20, (oldValue, newValue) -> oldValue + newValue);
        System.out.println(fruits); // {Apple=50, Banana=50}
    }
}

Output:

{Apple=50, Banana=50}

4. Use Cases

  • Caching: Storing key-value pairs for quick retrieval.
  • Database representation: Representing tables with rows as key-value pairs.
  • Configuration settings: Storing application settings as key-value pairs.

5. Best Practices

  • Use appropriate initial capacity: If the size of the map is known in advance, setting an initial capacity can improve performance.
  • Avoid frequent resizing: Adding elements frequently can cause resizing. Consider setting an appropriate initial capacity.
  • Use immutable keys: Using mutable objects as keys can lead to unpredictable behavior.

6. Performance Considerations

  • Constant-time performance: HashMap provides constant-time performance for basic operations like put, get, and remove.
  • Memory usage: Each entry in a HashMap requires additional memory for storing hash codes.
  • Thread safety: HashMap is not synchronized. Use Collections.synchronizedMap() or ConcurrentHashMap if thread safety is needed.

7. Real-time Example with CRUD Operations

Managing a Student Directory:

Student.java:

public class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

Main.java:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<Integer, Student> studentDirectory = new HashMap<>();

        // Create
        studentDirectory.put(1, new Student("Aarav", 20));
        studentDirectory.put(2, new Student("Vivaan", 22));
        studentDirectory.put(3, new Student("Diya", 21));

        // Read
        for (HashMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }

        // Update
        studentDirectory.put(2, new Student("Vivaan", 23));
        System.out.println("After Update:");
        for (HashMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }

        // Delete
        studentDirectory.remove(1);
        System.out.println("After Deletion:");
        for (HashMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }
    }
}

Output:

ID: 1, Student: Student{name='Aarav', age=20}
ID: 2, Student: Student{name='Vivaan', age=22}
ID: 3, Student: Student{name='Diya', age=21}
After Update:
ID: 2, Student: Student{name='Vivaan', age=23}
ID: 3, Student: Student{name='Diya', age=21}
After Deletion:
ID: 2, Student: Student{name='Vivaan', age=23}
ID: 3, Student: Student{name='Diya', age=21}

8. Conclusion

The HashMap class in Java is a powerful tool for managing key-value pairs. By understanding its methods, use cases, and best practices, you can effectively utilize HashMap in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments