Java HashMap

Java HashMap is a data structure that allows you to store key-value pairs. It is useful for mapping one value to another and retrieving values based on a key. In this blog, we will explore Java HashMap in detail, including how to declare and use it, and provide example code snippets to illustrate each concept.

Declaring a Java HashMap:

To declare a Java HashMap, you need to import the java.util.HashMap class and create an instance of it. Here is an example:

import java.util.HashMap;

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

In the above example, we declare a HashMap called map that maps strings to integers.

Adding Elements to a Java HashMap:

To add elements to a Java HashMap, you can use the put() method. Here is an example:

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

In the above example, we add three key-value pairs to the map.

Accessing Elements in a Java HashMap:

To access elements in a Java HashMap, you can use the get() method. Here is an example:

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

In the above example, we retrieve the value associated with the key “John”.

Removing Elements from a Java HashMap:

To remove elements from a Java HashMap, you can use the remove() method. Here is an example:

map.remove("Mary");

In the above example, we remove the key-value pair associated with the key “Mary”.

Iterating over a Java HashMap:

To iterate over a Java HashMap, you can use a for-each loop. Here is an example:

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

In the above example, we iterate over the keys in the map and retrieve the associated values.

HashMap vs HashTable:

HashMap and HashTable are both data structures used to store key-value pairs. HashMap is not synchronized, which makes it faster than HashTable. HashTable is synchronized, which makes it thread-safe.

Conclusion:

Java HashMap is a useful data structure that allows you to store key-value pairs and retrieve values based on a key. In this blog, we explored how to declare and use a Java HashMap, including how to add, access, and remove elements, as well as how to iterate over the map. We also compared HashMap with HashTable. If you need a data structure that is fast and not thread-safe, consider using a Java HashMap.