Top 15 Examples of HashMap in java | HashMap tutorial
This tutorial provides an overview of HashMap basics in Java, including its features and the top 15 examples.
Understanding How HashMap Works in Java
HashMap
serves as an implementation of the Map interface in Java and is widely used in the everyday life of java developers.
A HashMap
consists of pairs comprising a key
and its corresponding value
.
Both the key
and value
can be of types such as String, primitives, or any custom object.
The key’s storage within the HashMap
is determined by the hash code computed for its value.
HashMap is part of the Java Collections Framework and is defined in the java.util
package.
In programming contexts, HashMap is commonly employed as a temporary cache, typically within request or session scopes.
In programming, HashMap
is commonly used as a temporary cache, typically within request or session scopes.
Important Points to Remember for HashMap
- The order of keys stored in a HashMap is determined by hashing, although it’s not fixed.
- HashMap permits both null keys and null values.
- HashMap is not synchronized, meaning it’s not thread-safe.
- HashMap operates on a fail-fast principle. This means that if any modification (addition/removal) is attempted while iterating through the HashMap, it will throw a
ConcurrentModificationException
.
Keys are stored based on the outcome of the hashing mechanism.
How to Create a HashMap Object in Java?
HashMap provides two ways to create an object.
- Using the default constructor.
- Using a parameterized constructor with an initialCapacity specified as an integer number.
HashMap<String, String> map = new HashMap<>();
HashMap<String, String> map1 = new HashMap<>(10);
The first line initializes a HashMap
with a type of string using the default constructor, while the second line initializes it with an integer representing the initial capacity.
How to add Objects to HashMap
The HashMap
class provides the put
method to store key-value pairs in the map.
import java.util.HashMap;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("11", "oneone");
map.put("21", "twoone");
map.put("31", "threeone");
map.put("41", "fourone");
map.put("42", "fourone");
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
}
}
Important points to note.
- Keys do not allow duplicates.
- Values can be duplicated.
- It allows one null key and multiple null values.
How to Iterate Through Values in a HashMap
The HashMap
class provides the values()
method to iterate through all the values stored in the map.
Collection collection = map.values();
for (String str : collection) {
System.out.print(" " + str);
}
The values()
method returns a collection object that can be iterated over using a for-each loop to access each object. The output is.
twoone fourone threeone oneone
How to Find the Size of the HashMap
The size()
method is used to determine the size of the HashMap.
map.size()
This will return the size as 4 for the given map.
How to Check if a Key Exists in a HashMap
To determine if a specific key
exists in a HashMap
, we use the containsKey(Object obj)
method of the HashMap class.
If the key
is found in the map, it returns true
; otherwise, it returns false
.
map.containsKey("11"); // returns true
map.containsKey("134"); // returns false
How to Check if a Value Exists in a HashMap
To check if a specific value
exists in a HashMap, we use the containsValue(Object obj)
method of the HashMap
class.
If the value
is found, it returns true
; otherwise, it returns false.
map.containsValue("oneone") //return true
map.containsValue("cloudmap") //return false
How to Delete an Object from a HashMap
The remove
method provided by the map object removes a key and its corresponding value from the HashMap.
To delete an object from a HashMap, we use the remove(Object key)
method of the HashMap, which returns the value for that key if it exists.
It’s important to note that only the key object should be passed to the remove method. If the key is found, the method returns the value for that key; otherwise, it returns null.
String value=map.remove("21");
In the above example, if the key “21” is found in the map, it will remove that key-value pair and return the value object. If the key is not found, null is returned.
How to delete all the objects from the HashMap
To remove all the key
and value
pairs from the map
, use the clear()
method of HashMap
.
map.clear()
After clear()
method is used, if isEmpty()
is called , it returns true
as all the objects has been removed.
How to Converting Map keys to Set?
To convert the HashMap
keys to set
, we have to use keySet
which returns Set of keys
Set keys=map.keySet();
for(String str:keys){
System.out.print(" "+str);
}
How to Synchronize HashMap in java
HashMap
is not synchronized. that means more than one thread modifies the state of an object. But we can make HashMap as synchronized using synchronizeMap
Map synchronizedHashMap = Collections.synchronizeMap(map);
How to iterate hash map with for each loop
map.entrySet()
returns Set of Map.Entry<K,V>
which we can use in for loop. This iterates each item and prints key and values of an HashMap.
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}