
Java Hashmap in Java
HashMap in Java
A HashMap
is a part of Java's java.util
package and implements the Map
interface. It stores key-value pairs, where each key is unique, and each key maps to exactly one value. Internally, a HashMap
uses a hash table to store the entries, which allows for fast retrieval and insertion.
Key Characteristics of HashMap:
Unordered: A
HashMap
does not maintain the order of the elements. The order of the key-value pairs may change when new elements are added or removed.Allows null values: You can store
null
as both key and value.Allows only one
null
key: AHashMap
can have only onenull
key, but it can have multiplenull
values.Not synchronized: It is not thread-safe, meaning multiple threads should not modify it simultaneously.
Creating a HashMap
To create a HashMap
, you need to import it first from java.util
.
import java.util.HashMap;public class HashMapExample { public static void main(String[] args) { // Create a HashMap to store Integer keys and String values HashMap<Integer, String> map = new HashMap<>(); // Adding key-value pairs to the HashMap map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Printing the HashMap System.out.println(map); }}
Output:
{1=Apple, 2=Banana, 3=Cherry}
Basic HashMap Operations
1. put()
Method: Add elements to the HashMap.
map.put(4, "Date");
2. get()
Method: Retrieve a value by using its key.
String value = map.get(2); // Returns "Banana"System.out.println(value);
3. containsKey()
Method: Check if a key exists in the map.
boolean hasKey = map.containsKey(1); // Returns trueSystem.out.println(hasKey);
4. containsValue()
Method: Check if a value exists in the map.
boolean hasValue = map.containsValue("Apple"); // Returns trueSystem.out.println(hasValue);
5. remove()
Method: Remove an entry by key.
map.remove(3); // Removes key 3 and its associated value "Cherry"
6. size()
Method: Get the number of key-value pairs in the map.
int size = map.size(); // Returns the number of entries in the mapSystem.out.println(size);
7. clear()
Method: Remove all entries from the map.
map.clear(); // Clears all entries from the mapSystem.out.println(map);
Iterating Over a HashMap
There are several ways to iterate over a HashMap
.
1. Using forEach
method (Java 8 and above):
map.forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + value);});
2. Using entrySet()
: Iterating over the set of key-value pairs.
for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());}
3. Using keySet()
: Iterating over the keys.
for (Integer key : map.keySet()) { System.out.println("Key: " + key);}
4. Using values()
: Iterating over the values.
for (String value : map.values()) { System.out.println("Value: " + value);}
Example: HashMap with Custom Objects
You can also use custom objects as keys or values in a HashMap
. Here’s an example of using custom objects as values.
Example: HashMap with Custom Objects
import java.util.HashMap;class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Name: " + name + ", Age: " + age; }}public class HashMapWithCustomObject { public static void main(String[] args) { HashMap<Integer, Person> personMap = new HashMap<>(); // Adding Person objects to the HashMap personMap.put(1, new Person("Alice", 30)); personMap.put(2, new Person("Bob", 25)); // Accessing the Person object by key Person person = personMap.get(1); System.out.println(person); // Output: Name: Alice, Age: 30 }}
Thread-Safe Alternative: ConcurrentHashMap
If you need a thread-safe version of HashMap
, you can use ConcurrentHashMap
. Unlike HashMap
, ConcurrentHashMap
allows multiple threads to read and update the map concurrently.
HashMap vs TreeMap vs LinkedHashMap
HashMap
: Does not maintain any order.LinkedHashMap
: Maintains the insertion order or the access order.TreeMap
: Stores elements in a sorted order (based on natural ordering of keys or a comparator).
Conclusion
The HashMap
is one of the most commonly used collections in Java. It's fast for adding, removing, and looking up elements, making it a great choice when you need efficient key-value storage.
If you have any questions or need further examples on how to use HashMap
, feel free to ask! ?