Java HashMap is a collection class that implements the Map interface to store key-value pairs. It uses hash tables for efficient key lookup and offers constant-time performance for basic operations such as add, remove, and get.
It permits null values and keys and allows for the insertion of duplicate keys but not duplicate values. HashMap is not thread-safe, but it can be synchronized using the Collections.synchronizedMap() method.
To understand the more about Java HashMap, Read the Complete Article.
How to create a Java HashMap
Import the java.util.HashMap class
Create a new instance of the HashMap class
Add key-value pairs to the HashMap using the put() method
Retrieve the value associated with a key using the get() method
Remove a key-value pair from the HashMap using the remove() method
Check if a key is present in the HashMap using the containsKey() method
Recommended Java Topics to understand Java HashMap
Java Collections Framework
Java Generics
Java Map interface
Java Iterator interface
Advantages Of Java HashMap:
Efficient key-value storage and retrieval: HashMap provides an efficient way to store and retrieve key-value pairs in Java. It uses a hash table implementation, which allows for constant time complexity for basic operations such as put() and get().
Fast search and retrieval: HashMap provides fast search and retrieval of elements, since it uses hashing to index and store elements.
Dynamic size: HashMap can grow or shrink dynamically as elements are added or removed from it, making it more flexible than arrays.
Easy to use:HashMap is easy to use and provides a simple API for adding, retrieving, and removing elements from the map.
Methods of Java HashMap:
Methods
Description
put(key, value)
Adds a new key-value pair to the HashMap, or replaces the value if the key already exists.
get(key)
Returns the value associated with the specified key, or null if the key is not present in the HashMap.
containsKey(key)
Returns true if the HashMap contains the specified key, false otherwise.
size():
Returns the number of key-value pairs in the HashMap..
clear():
Removes all key-value pairs from the HashMap.
isEmpty():
Returns true if the HashMap contains no key-value pairs, false otherwise.
remove(key):
Removes the key-value pair associated with the specified key from the HashMap, if it exists.
values():
Returns a Collection containing all the values in the HashMap.
These are some methods that can be used to manipulate and access the elements in a HashMap.
Using the keySet() method: The keySet() method returns a Set view of the keys stored in the HashMap. You can iterate over this set of keys and retrieve the corresponding values from the HashMap using the get() method.
Using the entrySet() method: The entrySet() method returns a Set view of the key-value pairs stored in the HashMap as Map.Entry objects. You can iterate over this set of entries and retrieve the key and value from each entry.
Using Java 8 streams: If you are using Java 8 or later, you can use streams to iterate over the key-value pairs in a HashMap.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a new HashMap
HashMap<String, Integer> myMap = new HashMap<>();
// Add key-value pairs to the HashMap
myMap.put("apple", 1);
myMap.put("banana", 2);
myMap.put("orange", 3);
// Retrieve the value associated with a key
int value = myMap.get("banana");
System.out.println(value); // Output: 2
// Remove a key-value pair from the HashMap
myMap.remove("orange");
// Check if a key is present in the HashMap
boolean hasKey = myMap.containsKey("apple");
System.out.println(hasKey); // Output: true
// Iterate over the keys and values in the HashMap
for (String key : myMap.keySet()) {
int val = myMap.get(key);
System.out.println(key + " -> " + val);
}
// Clear all the key-value pairs from the HashMap
myMap.clear();
}
}
Output
2
true
banana -> 2
apple -> 1
Explanation:
In this program, we create a new HashMap object and add some key-value pairs to it using the put() method. We then retrieve the value associated with the key "banana" using the get() method, remove the key-value pair associated with the key "orange" using the remove() method, and check if the key "apple" is present in the HashMap using the containsKey() method.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// create a HashMap object
HashMap<String, Integer> myMap = new HashMap<>();
// add elements to the HashMap
myMap.put("apple", 1);
myMap.put("banana", 2);
myMap.put("orange", 3);
System.out.println("HashMap after adding elements: " + myMap);
// access elements from the HashMap
int appleValue = myMap.get("apple");
System.out.println("Value of 'apple': " + appleValue);
// change elements in the HashMap
myMap.put("banana", 4);
System.out.println("HashMap after changing 'banana': " + myMap);
// remove elements from the HashMap
myMap.remove("orange");
System.out.println("HashMap after removing 'orange': " + myMap);
}
}
Output
HashMap after adding elements: {banana=2, orange=3, apple=1}
Value of 'apple': 1
HashMap after changing 'banana': {banana=4, orange=3, apple=1}
HashMap after removing 'orange': {banana=4, apple=1}
Explanation:
In this program, we first create a new HashMap object and add three key-value pairs to it using the put() method. We then print out the HashMap to show the elements that were added.
Next, we access the value associated with the key "apple" using the get() method and print it out.
Then, we change the value associated with the key "banana" using the put() method, and print out the HashMap to show the change.
Finally, we remove the key-value pair associated with the key "orange" using the remove() method, and print out the HashMap to show the result.