In Java, HashMap
is a part of the java.util
package and provides a data structure that stores key-value pairs. It allows you to store elements based on unique keys and retrieve them quickly using those keys. Here's a basic overview of how to use HashMap
:
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { // Create a HashMap HashMapmap = new HashMap<>(); // Add key-value pairs to the HashMap map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Orange"); // Access elements in the HashMap System.out.println("Elements in the HashMap:"); for (Map.Entry entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } // Get the size of the HashMap int size = map.size(); System.out.println("Size of the HashMap: " + size); // Remove a key-value pair from the HashMap map.remove(2); // Check if a key exists in the HashMap boolean containsKey = map.containsKey(3); System.out.println("HashMap contains key 3: " + containsKey); // Check if a value exists in the HashMap boolean containsValue = map.containsValue("Banana"); System.out.println("HashMap contains value 'Banana': " + containsValue); // Clear all key-value pairs from the HashMap map.clear(); // Check if the HashMap is empty boolean isEmpty = map.isEmpty(); System.out.println("HashMap is empty: " + isEmpty); } }
This example demonstrates creating a HashMap
, adding key-value pairs to it, accessing elements, getting the size, removing key-value pairs, checking if a key or value exists, clearing the HashMap
, and checking if it's empty. HashMap
provides many more methods for manipulation and retrieval of key-value pairs.