HOME HTML EDITOR C JAVA PHP

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?

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

Difference Between HashMap and HashSet

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.