Interview
Interview
© Copyright by Interviewbit
Contents
What is a HashMap?
A collection based on the map which is used for storing key-value pairs in Java is
known as a HashMap. All the keys which are stored in a Hashmap are unique.
Let's see the syntax for how we can create a HashMap in Java:
Dave 16
Robin 19
Selena 32
Mark 10
As you can observe there is no ordering of names because hashmaps do not follow
any particular ordering for storing the elements.
Some important properties of a Hashmap in Java to remember:
Hashmaps are basically used for storing key-value pairs using a hashtable
Hashmap stores only unique keys
The is no particular ordering of elements in a HashMap
Import java.util.HashMap in your program for using a HashMap
Now in this article, we will be covering the most important and frequently asked Java
HashMap Interview Questions and Answers to help you ace the interviews. We will
cover different varieties of questions that cater to both freshers as well as
experienced programmers.
A hashmap uses a hashtable but what many people don’t know is that it is
internally created using two data structures namely an array and a linked list.
Whenever you declare a hashmap what is going to happen internally is that it
will create an array of buckets. The buckets are referred to as nodes or you can
say a linked list. These nodes contain mainly:
The key,
Value
Hashcode
Address of the next node.
Now, when you insert values in a key like this:
Then hashcode will be calculated by the put method. This hashcode will help us to
store the key at a particular index. Also, hashcode will make the process of retrieving
the values faster.
This hash code is further computed and will generate an index for storing the value.
The value of our key will be stored at the index given by the hashcode in the form of a
LinkedList.
It’s important to note that Java 8 introduced BST in place of a linked list to make
retrieval of the key-value pairs more efficient.
HashMap Vs HashTable
Performance Synchronization in a
hashtable might
sound like a good
idea that a particular
element would be
thread-safe if there’s
concurrent access
with multiple threads
You won't face
however, the
any
problem with
performance
synchronizing every
issues in a
method that allows
hashmap.
access to the
underlying collection
is that it creates
performance issues.
So you will have
performance issues
while using a
hashtable
import java.util.*;
import java.io.*;
public class interviewBit {
public static void main(String[] args)
{
HashMap hmap=new HashMap();
hmap.put(1,"Program to store null value");
hmap.put(null,"InterviewBit");
System.out.println(hmap);
}
}
OUTPUT:
There is no particular order for storing keys in a hashmap. All the keys are stored
in an unsorted order.
For storing the elements in a particular order a Treemap can be used in Java but
a hashmap does not guarantee the ordering of your elements.
import java.util.Map;
import java.util.HashMap;
Output:
import java.util.*;
import java.io.*;
public class interviewBit {
public static void main(String[] args)
{
HashMap hmap=new HashMap();
hmap.put(91,"Hashmap Implementation");
hmap.put(92,"in ");
hmap.put(93,"Java");
hmap.put(null,"InterviewBit");
System.out.println(hmap);
}
}
OUTPUT:
ConcurrentHashMap implementation:
For implementing ConcurrentHashmap we have to import the concurrent package.
import java.util.concurrent.ConcurrentHashMap;
public class interviewBit {
public static void main(String[] args)
{
ConcurrentHashMap hmap=new ConcurrentHashMap();
hmap.put(91,"Hashmap Implementation");
hmap.put(92,"in ");
hmap.put(93,"Java");
hmap.put(null,"InterviewBit");
System.out.println(hmap);
}
}
OUTPUT:
As we can observe from the above outputs we can store the null value in the
hashmap but it can’t be stored in a ConcurrentHashMap as it gives
NullPinterException.
import java.util.LinkedHashMap;
public class InterviewBit {
Hashmap Treemap
The ordering, of
In a hashmap, no ordering of elements is elements, is
maintained maintained in a
treemap.
We cannot store
We can store as many null values in a
any null values or
hashmap as we want but only 1 null key
keys in a
can be stored
treemap.
Treemap is
Hashmap uses arrays and LinkedList
implemented
which forms a hashtable for its
with the help of
implementation internally.
red-black trees.
A hashmap can be easily used to check whether the given arrays are equal or
not.
First, create a hashmap and using a for loop fill the frequency of each and every
element of array 1 in the hashmap.
Now, make another loop and decrement the frequency of each and every
element of the second array in the hashmap.
In the next step, iterate over the hashmap and check whether all the frequencies
are zero or not. Even if any frequency is 1 return false else return true.
A general approach for solving such kinds of problems is that first, you have to
create a map of Integers.
Then iterate through the given array and subtract the current value in the array
from the given target.
Look for that value in the hashmap simultaneously.
If the value is found in the map then return the index of these 2 numbers else
insert the current element of the array as the key and its index as the value in the
Hashmap.
Implementation:
class InterviewBit{
public int[] target(int[] nums, int t) {
HashMap<Integer, Integer> find_complement = new HashMap<>();
import java.util.HashMap;
public class InterviewBit
{
public static void main(String[] args)
{
HashMap<String, Integer> InterviewBit_map = new HashMap<String, Integer>();
InterviewBit_map.put("X", 1);
InterviewBit_map.put("Y", 2);
InterviewBit_map.put("Z", 3);
InterviewBit_map.put("W", 4);
int value = InterviewBit_map.get("Y");
System.out.println(value); //Output : 2
}
}
import java.io.*;
import java.util.*;
//Creating a hashmap
HashMap<Character, Integer> frequency_map = new HashMap<>();
for(int i = 0; i < str.length(); i++){
Character ch = str.charAt(i);
if(frequency_map.containsKey(ch) == true){
int old_freq = frequency_map.get(ch);
int new_freq = old_freq + 1;
frequency_map.put(ch, new_freq);
} else {
frequency_map.put(ch, 1);
}
}
System.out.println(c);
}
}
25. 4 sum using hashmap: You will be given four arrays arr1,
arr2, arr3, and arr4 all of length n,you have to return the
count of tuples (i, j, k, l) satisfying the conditions: 0 <= i, j, k,
l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Approach:
import java.util.*;
class Solution {
public int fourSumCount(int[] arr1, int[] arr2, int[] arr3, int[] arr4) {
HashMap<Integer, Integer> AB = new HashMap<>();
for (int val1 : arr1)
for (int val2 : arr2)
AB.put(val1 + val2, AB.getOrDefault(val1 + val2, 0) + 1);
int count = 0;
for (int val3 : arr3)
for (int val4 : arr4)
count += AB.getOrDefault(-val3 - val4, 0);
return count;
}
}
import java.util.HashMap;
public class InterviewBit
{
public static void main(String[] args)
{
HashMap<String, Integer> InterviewBit_map = new HashMap<String, Integer>();
InterviewBit_map.put("X", 1);
InterviewBit_map.put("Y", 2);
InterviewBit_map.put("Z", 3);
InterviewBit_map.put("W", 4);
27. Which method is used for finding out the total number of
key-value pairs present in a hashmap?Give example.
Size() method is used for finding out the total number of key-value pairs present in a
hashmap.
Example:
import java.util.HashMap;
InterviewBit_map.put("X", 1);
InterviewBit_map.put("Y", 2);
InterviewBit_map.put("Z", 3);
InterviewBit_map.put("W", 4);
System.out.println(InterviewBit_map.size()); //Output : 4
}
}
The find function will check whether any pair exists whose sum is
equal to a given value in O(N) average time whereas add function will
be used for adding any element in O(1) average time.
A hashmap will be the best choice for meeting our requirements as adding an
element can be performed in O(1) time whereas searching or finding an element can
be performed in O(N) time.
Implementation:
public TwoSum() {
our_map = new HashMap<>();
}
29. Which method is used for removing or deleting all the key-
value pairs? Write a program for removing all the key-value
pairs from a HashMap.
Clear() method is used for removing or deleting all the key-value pairs.
Implementation:
import java.util.HashMap;
InterviewBit_map.put("X", 1);
InterviewBit_map.put("Y", 2);
InterviewBit_map.put("Z", 3);
InterviewBit_map.put("W", 4);
InterviewBit_map.clear();
System.out.println(InterviewBit_map.size()); //Output : 0
}
}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Useful Resources
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions