Hash Map
Hash Map
Java HashMap class implements the Map interface which allows us to store key and value
pair, where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to
store the null elements as well, but there should be only one null key. Since Java 5, it is
denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the
AbstractMap class and implements the Map interface.
Points to remember
Constructor Description
Method Description
boolean replace(K key, V It replaces the old value with the new
oldValue, V newValue) value for a specified key.
1. import java.util.*;
2. public class HashMapExample1{
3. public static void main(String args[]){
4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashM
ap
5. map.put(1,"Mango"); //Put elements in Map
6. map.put(2,"Apple");
7. map.put(3,"Banana");
8. map.put(4,"Grapes");
9.
10. System.out.println("Iterating Hashmap...");
11. for(Map.Entry m : map.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Test it Now
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes
In this example, we are storing Integer as the key and String as the value, so we are
using HashMap<Integer,String> as the type. The put() method inserts the elements in the
map.
To get the key and value elements, we should call the getKey() and getValue() methods.
The Map.Entry interface contains the getKey() and getValue() methods. But, we should call
the entrySet() method of Map interface to get the instance of Map.Entry.
1. import java.util.*;
2. public class HashMapExample2{
3. public static void main(String args[]){
4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashM
ap
5. map.put(1,"Mango"); //Put elements in Map
6. map.put(2,"Apple");
7. map.put(3,"Banana");
8. map.put(1,"Grapes"); //trying duplicate key
9.
10. System.out.println("Iterating Hashmap...");
11. for(Map.Entry m : map.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Test it Now
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana