Java HashMap
HashMap is a part of the Java Collections Framework.
It is used to store data in key-value pairs.
HashMap belongs to the java.util package.
1. Why Use HashMap?
- Stores data in key-value format.
- Fast data access.
- No duplicate keys allowed.
- Allows one null key and multiple null values.
2. Importing HashMap
import java.util.HashMap;
3. Creating a HashMap
HashMap map = new HashMap();
4. Adding Elements (put method)
The put() method is used to add key-value pairs.
map.put("Apple", 100);
map.put("Banana", 50);
map.put("Mango", 80);
5. Accessing Elements (get method)
The get() method returns the value of a specific key.
System.out.println(map.get("Apple"));
6. Removing Elements (remove method)
map.remove("Banana");
7. Checking Key or Value
map.containsKey("Mango");
map.containsValue(100);
8. Looping Through HashMap
for(String key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
9. Size of HashMap
System.out.println(map.size());
10. Clear HashMap
map.clear();
Important Points
- HashMap does not maintain insertion order.
- Keys must be unique.
- Values can be duplicate.
- Not synchronized (not thread-safe).
Difference Between HashMap and HashSet
- HashMap stores key-value pairs.
- HashSet stores only unique values.
- HashMap uses put() method.
- HashSet uses add() method.
Example Program
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap marks = new HashMap<>();
marks.put("Rahul", 85);
marks.put("Amit", 90);
marks.put("Neha", 88);
for(String name : marks.keySet()) {
System.out.println(name + " : " + marks.get(name));
}
}
}
Conclusion
HashMap is a powerful class used to store data in key-value format.
It provides fast performance and is widely used in real-world applications.