Java HashMap Methods
In Java, HashMap is a part of the Collection Framework. It stores data in key-value pairs. Each key is unique, and it maps to a specific value.
HashMap belongs to the java.util package. So we must import it before using it.
1. Importing HashMap
import java.util.HashMap;
2. Creating a HashMap
HashMap students = new HashMap();
Here, String is the key type and Integer is the value type.
3. put()
The put() method is used to add key-value pairs.
students.put("Rahul", 85);
students.put("Amit", 90);
students.put("Neha", 95);
System.out.println(students);
4. get()
The get() method returns the value of a specific key.
System.out.println(students.get("Amit"));
5. remove()
The remove() method removes a key-value pair using the key.
students.remove("Rahul");
System.out.println(students);
6. containsKey() and containsValue()
containsKey() checks if a key exists.
containsValue() checks if a value exists.
System.out.println(students.containsKey("Neha"));
System.out.println(students.containsValue(90));
7. size()
The size() method returns the number of key-value pairs.
System.out.println(students.size());
8. clear()
The clear() method removes all entries from the HashMap.
students.clear();
System.out.println(students);
9. isEmpty()
The isEmpty() method checks if the HashMap is empty.
System.out.println(students.isEmpty());
10. keySet()
The keySet() method returns all keys in the HashMap.
HashMap map = new HashMap();
map.put("Java", 1);
map.put("Python", 2);
map.put("C++", 3);
System.out.println(map.keySet());
11. values()
The values() method returns all values in the HashMap.
System.out.println(map.values());
12. entrySet()
The entrySet() method returns all key-value pairs.
for (HashMap.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
Important Points About HashMap
- Keys must be unique.
- Values can be duplicate.
- HashMap does not maintain insertion order.
- It allows one null key and multiple null values.
- It is not synchronized (not thread-safe).
Difference Between HashMap and HashSet
- HashMap stores key-value pairs.
- HashSet stores only unique values.
- HashMap is used when you need mapping between two objects.
Conclusion
The HashMap class is very useful for storing and managing data using key-value pairs.
Common methods like put(), get(), remove(), containsKey(), keySet(), and entrySet() make it powerful and flexible.
Tip: Use HashMap when you need fast searching and mapping between keys and values.