Introduction:
HashMap is one of the most commonly used data structures in Java, offering efficient key-value pair storage and retrieval. Its versatility makes it indispensable in various programming scenarios, from basic data storage to complex algorithm implementations. In this technical blog, we’ll explore over 20 different use cases for HashMap in Java, accompanied by example code snippets to illustrate each scenario.
- Basic Key-Value Pair Storage:
HashMap provides a simple and efficient way to store key-value pairs:
import java.util.HashMap;
public class BasicHashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
hashMap.put("orange", 8);
System.out.println(hashMap);
}
}
- Accessing Values by Key:
You can retrieve values from a HashMap using their corresponding keys:
import java.util.HashMap;
public class AccessingValuesExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
hashMap.put("orange", 8);
int appleCount = hashMap.get("apple");
System.out.println("Number of apples: " + appleCount);
}
}
- Checking if a Key Exists:
You can check if a key exists in a HashMap:
import java.util.HashMap;
public class KeyExistsExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
boolean exists = hashMap.containsKey("apple");
System.out.println("Key 'apple' exists: " + exists);
}
}
- Removing Key-Value Pairs:
You can remove key-value pairs from a HashMap:
import java.util.HashMap;
public class RemoveKeyValueExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
hashMap.remove("apple");
System.out.println(hashMap);
}
}
- Iterating Over Key-Value Pairs:
You can iterate over all key-value pairs in a HashMap:
import java.util.HashMap;
import java.util.Map;
public class IterateHashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
hashMap.put("orange", 8);
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
- Checking if a Value Exists:
You can check if a value exists in a HashMap:
import java.util.HashMap;
public class ValueExistsExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
boolean exists = hashMap.containsValue(5);
System.out.println("Value '5' exists: " + exists);
}
}
- Getting the Size of a HashMap:
You can get the number of key-value pairs in a HashMap:
import java.util.HashMap;
public class HashMapSizeExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
int size = hashMap.size();
System.out.println("Size of HashMap: " + size);
}
}
- Clearing a HashMap:
You can remove all key-value pairs from a HashMap:
import java.util.HashMap;
public class ClearHashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
hashMap.clear();
System.out.println("HashMap after clearing: " + hashMap);
}
}
- Adding All Key-Value Pairs from Another Map:
You can add all key-value pairs from another map to a HashMap:
import java.util.HashMap;
import java.util.Map;
public class AddAllExample {
public static void main(String[] args) {
HashMap<String, Integer> originalMap = new HashMap<>();
originalMap.put("apple", 10);
originalMap.put("banana", 5);
HashMap<String, Integer> newMap = new HashMap<>();
newMap.put("orange", 8);
newMap.put("grape", 12);
originalMap.putAll(newMap);
System.out.println("Combined HashMap: " + originalMap);
}
}
- Getting All Keys:
You can retrieve all keys from a HashMap:
import java.util.HashMap;
import java.util.Set;
public class GetAllKeysExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
Set<String> keys = hashMap.keySet();
System.out.println("Keys: " + keys);
}
}
- Getting All Values:
You can retrieve all values from a HashMap:
import java.util.HashMap;
import java.util.Collection;
public class GetAllValuesExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 5);
Collection<Integer> values = hashMap.values();
System.out.println("Values: " + values);
}
}
- Checking if a HashMap is Empty:
You can check if a HashMap is empty:
import java.util.HashMap;
public class IsEmptyExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
System.out.println("HashMap is empty: " + hashMap.isEmpty());
hashMap.put("apple", 10);
System.out.println("HashMap is empty: " + hashMap.isEmpty());
}
}
- Getting a Default Value for a Key:
You can get a default value for a key if it doesn’t exist:
import java.util.HashMap;
public class GetOrDefaultExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 10);
int defaultValue = hashMap.getOrDefault("banana", 0);
System.out.println("Default Value: " + defaultValue);
}
}
- Using Custom Objects as Keys:
You can use custom objects as keys in a HashMap:
import java.util.HashMap;
class Person {
private String name;
public Person(String name) {
this.name = name;
}
// Override equals and hashCode methods
}
public class CustomObjectAsKeyExample {
public static void main(String[] args) {
HashMap<Person, Integer> hashMap = new HashMap<>();
Person person1 = new Person("Alice");
Person person2 = new Person("Bob");
hashMap.put(person1, 30);
hashMap.put(person2, 25);
System.out.println("Age of Alice: " + hashMap.get(person1));
}
}
- Handling Null Keys and Values:
HashMap allows null keys and values:
import java.util.HashMap;
public class NullKeysValuesExample {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(null, "value");
hashMap.put("key", null);
System.out.println("Null Key Value: " + hashMap.get(null));
System.out.println("Value for Key 'key': " + hashMap.get("key"));
}
}
- Using HashMap in Multithreaded Environments:
HashMap is not thread-safe, but you can use ConcurrentHashMap for multithreaded environments:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
Map<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("apple", 10);
concurrentHashMap.put("banana", 5);
System.out.println(concurrentHashMap);
}
}
- Handling Collisions:
HashMap handles collisions using chaining or open addressing:
import java.util.HashMap;
public class CollisionHandlingExample {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "apple");
hashMap.put(2, "banana");
hashMap.put(17, "orange"); // Collision with key 1
System.out.println(hashMap);
}
}
- Specifying Initial Capacity and Load Factor:
You can specify the initial capacity and load factor of a HashMap:
import java.util.HashMap;
public class CapacityLoadFactorExample {
public static void main(String[] args) {
int initialCapacity = 16;
float loadFactor = 0.75f;
HashMap<String, Integer> hashMap = new HashMap<>(initialCapacity, loadFactor);
hashMap.put("apple", 10);
hashMap.put("banana", 5);
System.out.println(hashMap);
}
}
- Restricting the Types of Keys and Values:
You can restrict the types of keys and values in a HashMap using generics:
import java.util.HashMap;
public class GenericHashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
// Only String keys and Integer values are allowed
hashMap.put("apple", 10);
hashMap.put("banana", 5);
System.out.println(hashMap);
}
}
- Using LinkedHashMap for Ordered Iteration:
LinkedHashMap maintains the insertion order of elements:
import java.util.LinkedHashMap;
public class LinkedHashMapExample {
public static void main(String[] args) {
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("apple", 10);
linkedHashMap.put("banana", 5);
linkedHashMap.put("orange", 8);
System.out.println(linkedHashMap);
}
}
Conclusion:
HashMap is a versatile data structure in Java, offering a wide range of functionalities for storing and manipulating key-value pairs. From basic operations like insertion and retrieval to advanced features like handling collisions and multithreading, HashMap provides an efficient solution for various programming challenges. By understanding its capabilities and leveraging its flexibility, developers can build robust and scalable applications across diverse domains.

Leave a Reply