A HashMap in Java is a data structure that stores key-value pairs, where each key is unique. It is implemented using a hash table, which allows for fast access, insertion, and deletion of elements. Here is an example of how to create and use a HashMap in Java.
First, we need to import the HashMap class:
import java.util.HashMap;
Next, we can create a new HashMap object. We can specify the types of the keys and values when we create the object:
HashMap<String, Integer> map = new HashMap<>();
In this example, the keys are of type String, and the values are of type Integer.
We can add key-value pairs to the map using the put method:
map.put("apple", 5);
map.put("banana", 3);
map.put("orange", 2);
We can retrieve a value by its key using the get method
int appleCount = map.get("apple");
We can check if a key is present in the map using the containsKey method:
boolean hasApple = map.containsKey("apple");
We can remove a key-value pair from the map using the remove method:
map.remove("banana");
Finally, we can iterate over all the key-value pairs in the map using the entrySet method:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
Keep in mind that a HashMap does not maintain the insertion order of the elements, and the order of the elements may change over time. If you need to maintain the insertion order of the elements, you can use a LinkedHashMap instead.
Also, the HashMap is not thread safe, if you want to use it in a multi-threaded environment, you can use ConcurrentHashMap which is thread-safe.
Hope this tutorial helps you to understand HashMap and its functionality in Java.