Write a program in Java to implement HashMap.

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2021-04-19 09:12:15 Viewed : 486


HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).  Let’s see how to implement HashMap logic in Java with the help of below program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package runnerdev;
 
import java.util.HashMap;
import java.util.Map;
 
public class Hashmap
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
print(map);
map.put("abc", 10);
map.put("mno", 30);
map.put("xyz", 20);
 
System.out.println("Size of map is" + map.size());
 
print(map);
if (map.containsKey("abc"))
{
Integer a = map.get("abc");
System.out.println("value for key "abc" is:- " + a);
}
map.clear();
print(map);
}
public static void print(Map<String, Integer> map)
{
if (map.isEmpty())
{
System.out.println("map is empty");
}
else
{
System.out.println(map);
}
}
}

On executing the HashMap program, output goes like this:

1
2
3
4
5
map is empty
Size of map is:- 3
{abc=10, xyz=20, mno=30}
value for key "abc" is:- 10
map is empty

Search
Related Articles

Leave a Comment: