Java HashMap

In Java, HashMap is a built-in implementation of the Map interface that uses a hash table to store its elements. HashMap allows you to store key-value pairs, where the key is unique and the value can be any object. Here’s an explanation of HashMap in Java with examples:

Creating a HashMap

To create a HashMap object in Java, you can use the HashMap class constructor. Here’s an example:

HashMap<String, Integer> map = new HashMap<String, Integer>();

In this example, we have created a new HashMap object that can hold String keys and Integer values.

Adding and Removing Elements

You can add elements to a HashMap object using the put method. Here’s an example:

map.put("John", 25);
map.put("Mary", 30);

In this example, we have added two key-value pairs to the HashMap.

You can remove elements from a HashMap object using the remove method. Here’s an example:


In this example, we have removed the key-value pair with the key “Mary” from the HashMap.

Accessing Elements

You can access elements in a HashMap object using the get method. Here’s an example:

int age = map.get("John");

In this example, we have retrieved the value associated with the key “John” from the HashMap and stored it in an int variable called age.

Iterating Over a HashMap

You can iterate over the key-value pairs in a HashMap object using a for loop or an iterator. Here’s an example using a for loop:

for (String name : map.keySet()) {
    int age = map.get(name);
    System.out.println(name + " is " + age + " years old.");

In this example, we have used a for loop to iterate over the keys in the HashMap, retrieved the corresponding values using the get method, and printed the results to the console.

Checking for Key Existence

You can check if a key exists in a HashMap object using the containsKey method. Here’s an example:

boolean exists = map.containsKey("John");

In this example, we have checked if the key “John” exists in the HashMap and stored the result in a boolean variable called exists.

Hashing and Equality

HashMap uses the hashCode and equals methods of the keys it contains to determine if two keys are equal. It uses the hashCode method to place keys in the hash table and the equals method to check for equality. For this reason, it is important to implement the hashCode and equals methods correctly in your key objects if you plan to use them in a HashMap.

The HashMap class in Java provides a powerful and efficient way to store and manipulate key-value pairs. By using the HashMap class, you can write code that can perform complex operations on the map efficiently and without worrying about duplicates.

A quick recap of Java