Java HashMap

What is HashMap?

In Java, a HashMap is part of the Java Collections Framework and is one of the most commonly used data structures. It is a collection of key-value pairs, where each key is unique, and each key maps to a specific value. A HashMap is a powerful tool for performing fast lookups, adding or removing elements, and is widely used in applications where quick access to data is essential.

Why Use a HashMap in Java?

A HashMap is used when you need to store data in pairs (key-value) and retrieve values efficiently based on keys. It offers the following advantages:

  • Fast Access: The HashMap allows for constant-time performance (O(1)) for basic operations like get() and put(), making it very efficient.
  • No Duplicate Keys: A HashMap doesn’t allow duplicate keys, ensuring that each key maps to a unique value.
  • Flexible Storage: You can store any type of objects as both keys and values, providing flexibility in how data is organized.

How Does a HashMap Work?

Internally, a HashMap works by using an array of buckets to store key-value pairs. When a key-value pair is inserted, the key is hashed (using a hashing function), and this hash value determines the index in the internal array where the pair is stored. This hashing technique provides very fast lookups.

Key points to remember:

  • Keys must be unique in a HashMap. If you try to insert a pair with an existing key, the old value will be replaced.
  • Null Values: A HashMap allows one null key and any number of null values.

Creating a HashMap

In Java, you can create a HashMap by using the following syntax:

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

Here, KeyType is the type of the key, and ValueType is the type of the value you want to store.

Example: Creating a HashMap of Integer Keys and String Values

import java.util.*;

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

// Adding key-value pairs to the map
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

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

Output:

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

Common Operations in HashMap

Here are the most commonly used methods in the HashMap class:

  1. put(K key, V value): Adds a key-value pair to the map. If the key already exists, it updates the value.
  2. get(Object key): Retrieves the value associated with the key.
  3. remove(Object key): Removes the key-value pair associated with the given key.
  4. containsKey(Object key): Checks if the map contains the specified key.
  5. size(): Returns the number of key-value pairs in the map.
  6. clear(): Removes all entries from the map.

Example: Using Common HashMap Methods

import java.util.*;

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

// Retrieving a value
String value = map.get(2);
System.out.println("Value for key 2: " + value);

// Checking if a key exists
boolean containsKey = map.containsKey(3);
System.out.println("Map contains key 3: " + containsKey);

// Removing a key-value pair
map.remove(1);
System.out.println("Updated HashMap: " + map);

// Getting the size of the map
System.out.println("Size of the map: " + map.size());

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

Output:

Value for key 2: Banana
Map contains key 3: true
Updated HashMap: {2=Banana, 3=Cherry}
Size of the map: 2
Cleared HashMap: {}

Iterating Over a HashMap

You can iterate over a HashMap in various ways, such as:

  • Using for-each loop: To iterate over keys or values.
  • Using Iterator: For more control over the iteration process.
  • Using forEach() method: A method introduced in Java 8 to iterate over the map entries.

Example: Iterating Over a HashMap

import java.util.*;

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

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

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

Output:

1: Apple
2: Banana
3: Cherry
1: Apple
2: Banana
3: Cherry

HashMap vs Hashtable

Both HashMap and Hashtable are used to store key-value pairs, but there are some important differences:

  • Thread Safety: Hashtable is synchronized, making it thread-safe, whereas HashMap is not synchronized by default.
  • Null Keys and Values: HashMap allows one null key and multiple null values, but Hashtable does not allow any null keys or values.

In most cases, HashMap is preferred for non-threaded environments due to its better performance. If thread safety is required, you can use ConcurrentHashMap or synchronize the HashMap manually.

Leave a Comment