HashMap in Java
Java HashMap class implements the Map interface which lets us store the key and value pair. In this case, the keys should be unique, any kind of duplication will result in the replacement of the corresponding key.
This concept has been a part of Java’s collection since Java 1.2. The java.util package contains the HashMap<K,V> class. Accessing the keys takes place using its indices.
The concept of HashMap is a bit alike the HashTable. The only difference is that the HashMap is not synchronized. We can also store null keys, but the null key object should be only one whereas, the null values can be many.
Declaration of a HashMap in Java:
This is how we declare java.Util.HashMap class
public class HashMap<K, V> extends, Abstrctmap<K,V> implements Map<K,V>, Cloneable, Serializable
Parameters of a HashMap Class:
The java.util.HashMap class takes a couple of parameters as follows:
- K: The key type that the map contains
- V: The type of the mapped values
Constructors of Java HashMap class:
Methods of Java HashMap class:
Java HashMap Sample Program:
import java.util.*;
public class DFHashMap1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>(); //HashMap creation
map.put(1,"Java");
//Adding elements to Map
map.put(2,"Python");
map.put(3,"C");
map.put(4,"C++");
System.out.println("Hashmap Iteration takes place");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Hashmap Iteration takes place
1 Java
2 Python
3 C
4 C++
No Duplicate Key on HashMap:
import java.util.*;
public class DFHashMap2{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>(); //HashMap creation
map.put(1,"Java");
//Put elements in Map
map.put(2,"Python");
map.put(3,"C");
map.put(1,"C++"); // duplication of key
System.out.println("Hashmap iteration takes place");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Hashmap Iteration takes place
1 Java
2 Python
3 C
4 C++
Java HashMap Sample to implement add() method:
import java.util.*;
class DFHashMap3{
public static void main(String args[]){
HashMap<Integer,String> h=new HashMap<Integer,String>();
System.out.println("Initial set of values: "+h);
h.put(100,"Java");
h.put(101,"Python");
h.put(102,"C++");
System.out.println("After invoking put() method ");
for(Map.Entry m:h.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
h.putIfAbsent(103, "CSS");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:h.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"JavaScript");
map.putAll(h);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Initial set of values: {}
After invoking put() method
100 Java
101 Python
102 C++
After invoking putIfAbsent() method
100 Java
101 Python
102 C++
103 CSS
After invoking putAll() method
100 Java
101 Python
102 C++
103 CSS
104 JavaScript
Java HashMap Sample to implement remove() method:
import java.util.*;
public class DFHashMap4 {
public static void main(String args[]) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Java");
map.put(101,"Python");
map.put(102,"C++");
map.put(103, "JavaScript");
System.out.println("Initial set of values: "+map);
map.remove(100);
System.out.println("Updated set of values: "+map);
map.remove(101);
System.out.println("Updated set of values: "+map);
map.remove(102, "C++");
System.out.println("Updated set of values: "+map);
}
}
Output:
Initial set of values: {100=Java, 101=Python, 102=C++, 103=JavaScript}
Updated set of values: {101=Python, 102=C++, 103=JavaScript}
Updated set of values: {102=C++, 103=JavaScript}
Updated set of values: {103=JavaScript}
Java HashMap sample to implement replace() method:
import java.util.*;
class DFHashMap5{
public static void main(String args[]){
HashMap<Integer,String> h=new HashMap<Integer,String>();
h.put(100,"Java");
h.put(101,"Python");
h.put(102,"C++");
System.out.println("Initial set of values:");
for(Map.Entry m:h.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated set of values:");
h.replace(102, "HTML");
for(Map.Entry m:h.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated set of values:");
h.replace(101, "HTML", "JavaScript");
for(Map.Entry m:h.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated set of values:");
h.replaceAll((k,v) -> "ReactJS");
for(Map.Entry m:h.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Initial set of values:
100 Java
101 Python
102 C++
Updated set of values:
100 Java
101 HTML
102 C++
Updated set of values:
100 Java
101 JavaScript
102 C++
Updated list of elements:
100 ReactJS
101 ReactJS
102 ReactJS
Difference between HashSet and HashMap in Java:
The main difference between HashSet and HashMap is that the former contains only values whereas, the latter consists of values and keys.
Features of a HashMap in Java
Before getting to know about the various features that HashMap provides, let us see what hashing is. Hashing is a technique by which we can convert a large String to a smaller String. It represents the same String but with a shorter value as it is useful in indexing and performing quicker searches. A HashMap uses this hashing technique.
Here are a few features of HashMap:
- It is present in the java.util.package.
- It implements a Cloneable and Serializable interface.
- It does not allow duplication of keys but also duplication of values. This means, a single key cannot contain multiple values, but more than one key can contain the same value.
- HashMap allows a null key for once and multiple values.
- It extends the abstract class AbstractMap which provides an unfinished implementation of the Map interface.
- It provides no guarantee that the order of the map will remain constant.
Internal structure of a HashMap:
Internally, a HashMap consists of an array of Node and a node that is given as a class with four fields. These four fields include:
1. int hash
2. K key
3. V value
4. Node next
As the node has a reference to its own object, it is a linked list.
Performance of Java HashMap:
A couple of factors determine the performance of a HashMap. These two factors are:
1. Initial Capacity
2. Load Factor
1. Initial Capacity
It is the HashMap’s capacity during the time of its creation. It denotes the number of buckets a HashMap can hold when it is created. In java, a HashMap can initially hold 16 key value pairs, that is, 2^4.
2. Load Factor
It is the percent value of the capacity after which the capacity of HashMap will be increased. In the default manner, the rehearsing takes place after filling 75% of the capacity.
The other two factors are:
3. Threshold
Threshold is the product of the Load Factor and Initial Capacity. By default, it is (16 * 0.75 = 12). Rehashing takes place once the insertion of 12 key-value pairs into the HashMap.
4. Rehashing
This process doubles the capacity of the HashMap once it reaches the Threshold. It HashMap continues to rehash in the sequence – 2^4, 2^5, 2^6, 2^7, and so on.
Synchronized HashMap:
The HashMap is unsynchronized. This means it has various threads accessing it simultaneously. When this takes place, at least a single thread manipulates the HashMap structurally to synchronize it externally. This process is done by synchronizing some object that encapsulates the HashMap.
For example:
Map m = Collections.synchronizedMap(new HashMap(…));
Here, Map m is synchronized. In the event of any structure modification, the iterators in this class would fail. The only way to avoid this is by implementing the iterator’s remove method. In this case, it throws ConcurrentModificationException.
The time complexity of HashMap:
The time complexity that HashMap provides is constant for basic operations like get, and put. Iteration using HashMap varies according to its capacity and the count of key-value pairs. Most often, the iteration is directly proportional to the sum of capacity and size. Capacity is based on the number of buckets in HashMap. Therefore, it is not advisable to hold many buckets in HashMap.
Conclusion:
This is all about HashMap in Java. you can try the sample program provided in this article to know how this concept is being implemented.
