Curriculum
HashMap is a class in Java that implements the Map interface. It is used to store key-value pairs, where each key is unique and associated with a value. HashMap is an implementation of a hash table data structure, which provides fast access to the key-value pairs based on the hash value of the keys.
Here’s an example of how to use HashMap in Java:
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { // create a HashMap to store names and ages HashMap<String, Integer> ages = new HashMap<>(); // add entries to the HashMap ages.put("Alice", 25); ages.put("Bob", 30); ages.put("Charlie", 35); // retrieve a value from the HashMap int aliceAge = ages.get("Alice"); System.out.println("Alice's age is " + aliceAge); // remove an entry from the HashMap ages.remove("Bob"); // iterate over the entries in the HashMap for (String name : ages.keySet()) { int age = ages.get(name); System.out.println(name + " is " + age + " years old."); } } }
In this example, we first import the HashMap class from the java.util package. Then, we create a new instance of a HashMap called ages
, which will store the ages of different people.
We then add three entries to the HashMap using the put()
method, where the keys are the names of the people and the values are their ages. We can retrieve the age of a specific person using the get()
method.
We then remove an entry from the HashMap using the remove()
method, which removes the entry associated with the key “Bob”.
Finally, we iterate over the entries in the HashMap using a for-each loop, where we use the keySet()
method to get a set of all the keys in the HashMap, and then retrieve the value associated with each key using the get()
method. We then print out a message for each entry that displays the name and age of the person.
Overall, HashMap is a useful data structure in Java for storing and accessing key-value pairs, and it is widely used in many Java applications.