How Java 8 Helps in Improving Performance of HashMap?
Last Updated :
17 Jun, 2021
Here we will be discussing out how we can, we improve the performance while using HashMap in Java, the Importance of the hashCode() contract and why is it very important to have an efficient hashcode, and what happens when we use an in-efficient hashcode. Let us directly roll over to implementing the same over the same set size of keys in our HashMap. It is as follows:
Implementation: Here no such concept is introduced, so a naive approach is being applied over our HashMap.
Example 1:
Java
// Java Program to Illustrate In-efficient Technique
// While using HashMap
// Importing Map and HashMap utility classes
// from java.util package
import java.util.HashMap;
import java.util.Map;
// Main class
class HashMapEx2 {
// main driver method
public static void main(String[] args)
{
// Creating a Map object
// Declaring object of user-defined class and string
// type
Map<Student, String> studentMap = new HashMap<>();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
studentMap.put(new Student("saty" + i),
"satyy" + i);
}
studentMap.forEach(
(k, v) -> System.out.println(k + " : " + v));
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println(
"\n Execution time in milliseconds for In-Efficient hashcode : "
+ timeElapsed + " milliseconds.");
}
}
/*Student class.*/
class Student {
String name;
public Student(String name)
{
super();
this.name = name;
}
@Override public String toString()
{
return "Student [name=" + name + "]";
}
/* Very in-efficient hashcode override */
@Override public int hashCode()
{
return 12; /* Very inefficient hashcode, returns 12
for every key, that means all the keys
will end up in the same bucket */
}
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student)obj;
if (name == null) {
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
}
Output: It contains humongous lines as the output to illustrate milliseconds taken hence, the last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:
Output Explanation: In the above program, we use Student as a HashMap key and the hashCode() override in the Student class is written very inefficiently which returns the same hashcode for every Student object.Â
Why an efficient hashcode is so darn important?
When you run the above program, what actually happens behind the scene is that when the HashMap is created it stores all the 10000 keys of student objects into the same bucket. As a result, all the keys get stored on a single bucket which results in a huge performance hit, and you can see that the time taken for the execution of the first program is approx 1700 milliseconds.
Now, in the program below, our hashcode override in the Student class is efficient and returns unique hashcode for every Student Object. As a result, each hashmap key is stored in a separate bucket, which improves the performance by 'n' times for storing the keys, and you can see that the time taken for the execution of the second program is only about 300 milliseconds
Example 2:
Java
// Java Program to Illustrate In-efficient Technique
// While using HashMap
// Importing Map and HashMap utility classes
// from java.util package
import java.util.HashMap;
import java.util.Map;
// Main class
class HashMapEx3 {
// main driver method
public static void main(String[] args)
{
Map<Student, String> studentMap = new HashMap<>();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
studentMap.put(new Student("saty" + i),
"satyy" + i);
}
studentMap.forEach(
(k, v) -> System.out.println(k + " : " + v));
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println(
"\n Execution time in milliseconds for Efficient hashCode: "
+ timeElapsed + " milliseconds");
}
}
/*Student class.*/
class Student {
String name;
public Student(String name)
{
super();
this.name = name;
}
@Override public String toString()
{
return "Student [name=" + name + "]";
}
/* Efficient hashcode override */
@Override public int hashCode()
{
return name.hashCode()
* 12; /* Efficient hashcode, returns unique
hashcode for every key, that
means the keys will be distributed into
unique buckets */
}
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student)obj;
if (name == null) {
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
}
Output: It contains humongous lines as the output to illustrate milliseconds taken hence, last snapshot off the output roll is appended below in order to figure out the time taken for all the operations. It is as follows:
We can figure out a significant change wherein example 1 takes close to 1700 milliseconds and here as depicted from the output, it takes close to 180 seconds only. Hence, the multiplier of 10X is justified when we compare the above-demonstrated examples.
Similar Reads
Internal Working of HashMap in Java
In this article, we will understand the internal workings of the HashMap in Java, also how the get() and put() method functions, how hashing is done, how key-value pairs are stored, and how the values are retrieved by keys.Basic Structure of a HashMapHashMap contains an array of Node objects. Each n
10 min read
How HashTable Works Internally in Java?
Hashtable is a kind of Hash map but is synchronized. Hash map is nonâsynchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, Â the key/values pairs are stored in Hashtable. The Hash table does not allow null
12 min read
First Step in Evaluating Java Performance Issue
Among all the programming languages used around the world, Java is one of the most widely used. It is known for its versatility and ability to run on a variety of platforms, making it an ideal choice for a wide range of applications. However, like any other programming language, Java can experience
6 min read
How to check if a key exists in a HashMap in Java
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient): Get the HashMap a
4 min read
How Does ConcurrentHashMap Achieve Thread-Safety in Java?
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class Co
6 min read
HashMap and TreeMap in Java
HashMap and TreeMap are part of collection framework. HashMapjava.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair<Key, Value>. HashMap<K, V> hmap = new HashMap<K, V>(); Let us consider below example where we have to count occurrences
5 min read
Why String is popular HashMap key in Java?
There are many instances when data is stored as key-value pairs. In Java, it can be achieved by "map" which is a collection. Keys usually should not be null and they should point to only one value. In Map, there are various classes available and among them, Hashmap is a class that implements the Map
3 min read
HashMap values() Method in Java
The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters. Return Value: The method i
2 min read
Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add
10 min read
Hashmap vs WeakHashMap in Java
HashMap Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates o
3 min read