Top 51+ Java Map Interview Questions Answers For 0 to 5 Years Experience Candidate

In the previous article, I wrote about Top 35+ Java Set Interface Interview Questions Answers for 0 to 5 years Experience In this article, I am going to share Top 51+ Java Map Interview Questions Answers For 0 to 5 Years Experience frequently asked on Interview. You can expect many questions from this topic in the interview.

 

Q1. What is a Map in Java?
Ans:
Map is an interface of a collection in java. Map interface in java store the value as key and value pair.

Q2. Do Map is the child of a collection in java?
Ans:
Map interface is not a child of the collection because of Map store value as key and value pair. Here key and values are an object.

Q3. Can we duplicate the key and value?
Ans:
Key cannot be duplicated but a value can be duplicated in Map.

Q4. What do you understand by an entry in Map?
Ans:
Each key and value pair is called as an entry. A map is a collection of entry.

Q5. Does Map use the collection’s methods?
Ans:
No, Map has its own methods we can’t use the methods of collection.

Q6. List our the Map method?
Ans:
The list of Map interface methods are as follows:

Method

Description

put(Object key, Object value) This is used to insert an entry in the map.
putAll(Map map) Used to insert the specified map in the map.
putIfAbsent(K key, V value) This method inserts the specified value with the specified key in the map only if it is not already specified.
void remove(Object key) This is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map.
Set keySet() This method returns the Set view containing all the keys.
void clear()

It is used to reset the map.

boolean contains value(Object value) This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) Returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) This method used to compare the specified Object with the Map.
get(Object key) Returns the object that contains the value associated with the key.
int hashCode() This method returns the hash code value for the Map
boolean isEmpty() Returns true if the map is empty; returns false if it contains at least one key.
void replace(K key, V value) This method replaces the specified value for a specified key.

Q7. What is Entry interface in Map?
Ans:
Entry is the interface of Map. It returns a collection-view of the map. It provides methods to get key and value.

Q8. What are the methods of Entry interface
Ans:
Methods of Map. Entry Interface is listed below:

Method Description
getKey() This is used to obtain a key.
getValue() It is used to obtain value.
Int hashCode() This is used to obtain hashCode
Boolean equals(Object o) It is used to compare the specified object with the other existing objects.

Q9. Write an example program to store the object in the Map and also to retrieve the object?
Ans:

 import java.util.*;
class Xadmin
{
public static void main(String args[])
{
Mao<Integer, String> map= new HashMap<Integer, String>();
map.put(100,”xadmin1”);
map.put(101,”xadmin2”);
map.put(102,”xadmin3”);
for(Map.Entry m: map.entrySet())
{
System.out.println(m.getKey()+” ”+ m.getValue());
}
}
}

Q10. What is HashMap in Java?
Ans:
HashMap class in java implement the map interface by using a hash table.

Q11. What are the properties of the HashMap in Java Collection?
Ans:
The properties of the HashMap are as follows:

  • HashMap store the element in the form of key and value pair format.
  • It stores the element in indexing representation.
  • In HashMap key can’t be duplicated but a value can be duplicated.
  • Heterogenous value allowed for key and value.
  • It stores the value in an unordered way.
  • Null is allowed for value and key.
  • In implement cloneable interface.

Q12. Where to use HashMap?
Ans:
The best choice to use the HashMap is in a search operation. As the searching operation is fast.

Q13. What are the constructors of the HashMap?
Ans:
Constructor for the HashMap

  • HashMap m = new HashMap();
  • HashMap m = new HashMap(int initial capacity);
  • HashMap m = new HashMap(int initial capacity, float fill ration);
  • HashMap m = new HashMap(Map m);

Q14 What is the default capacity of the HashMap?
Ans:
Default capacity of the HashMap is 16.

Q15. What is the Default fill ration of the HashMap?
Ans:
Default fill ration is 0.75% this means after filling the 75% of the total capacity. HashMap will create new capacity.

Q16. Difference between HashMap and HashTable?
Ans:

HashMap

HashTable

Methods of HashMap are not synchronized Methods of HashTable are synchronizes
It is not threadsafe. Multiple threads allow executing It is thread-safe. Multiple threads not allowed to execute.
Performance is high Performance is low
Only one null as a key is allowed and null values are allowed No null as key or value is allowed
It is not a legacy class. It comes in 1.2v It is of legacy class. It comes in 1.0v

Q17. How to get a Synchronized version of the Hash Map Object.?
Ans: HashMap m = new HashMap();
Map m1= Collections.synchronizedmap(m);

Q18. What is LinkedHashMap in Java?
Ans:
LinkedHashMap class of java is Hashtable and Linked list implementation of the Map interface. It inherits the HashMap class and implements the Map interface.

Q19. What are the properties of the LinkedHashMap?
Ans:
The properties of the LinkedHashMap is listed below:

  • LinkedHashMap stores the values in key and value pair.
  • LinkedHashMap contains a unique element.
  • It can only store one key as null and multiple nulls as values.
  • This is non-Synchronized.
  • Its stores the element in insertion order.
  • The default capacity of the LinkedHashMap is 16 and its load factor is 0.75.

Q20. What is the Syntax of the LinkedHashMap class?
Ans: The syntax of the LinkedHashMap class is:

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

Q21. What is the Constructor of the LinkedHashMap class?
Ans:
Constructor of the LinkedHashMap class are as follows:

  • LinkedHashMap(): It is used to create a default object of the LinkedHashMap.
  • LinkedHashMap(int capacity(): This constructor will initialize
  • LinkedHashMap(int capacity, float load_factor): This method is used to initialize both the capacity and the load factor
  • LinkedHashMap(int capacity, float load_Factor, boolean access_order): It is used to initialize both the capacity and the load factor with specified ordering mode.

Q22. What are the methods of the LinkedHashMap?
Ans:
Method of LinkedHashMap class in java is as follows:

Method

Description

Object get(Object key) This method returns the value to which the specified key in mapped
void clear() It removes all the key-value pairs from a map
boolean contains value(Object value) This returns true if the map maps one or more keys to the specified value
Set entrySet() This returns a set view of the mappings contained in the map
Set keySet() It returns a set view of the keys contained in the map
Collection values() It returns a Collection view of the values contained in this map.

Q23. Write a small program to store the object and retrieve the object from the LinkedHashMap?
Ans:

import java.util.*;  
class XadminLinkedHashMap
{  
 public static void main(String args[])
 {  
   LinkedHashMap<Integer,String> Xadhm=new LinkedHashMap<Integer,String>();  
  
  Xadhm.put(100,"Xadmin1");  
  Xadhm.put(101,"Xadmin2");  
  Xadhm.put(102,"Xadmin3");  
  
for(Map.Entry m:Xadhm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
System.out.println(“invoking remove method”);
       m.remove(102);
for(Map.Entry m:Xadhm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

Output:
100 Xadmin1
101 Xadmin2
102 Xadmin3
invoking remove method
100 Xadmin1
101 Xadmin2

Q24. Difference between HashMap and LinkedHashMap
Ans:

HashMap LinkedHashMap
Underlying DataStructure is HashTable An underlying data structure is LinkedHashMap and HashTable
Store elements in an unordered way Store elements in an ordered way
Introduced in 1.2v introduced in 1.4v

Q25. What is IdentityHashMap in java
Ans:
IdentityHashMap class implements AbstractMap. It is similar to HashMap except that it uses reference equality when comparing the stored elements.

Q26. How the HashMap identify the duplicate object?
Ans:
In HashMap JVM uses equals methods to identify the duplicate key
For Example:

HashMap m = new HashMap();
Integer I1 = new Integer(10);
Integer I2 = new Integer(10);
m.put(I1,”Xadmin”);
m.put(I2,”Ashish”);
System.out.println(m);

In the above code, JVM will identify the duplicate key by equals() method as I1.equals(I2). This return true as I1 and I2 values is equal so duplicate key entered above.
So the output of the above code will be {10, Ashish}

Q27. How the IdentifyHashMap checks the duplicate element?
Ans: In IdentityHashMap JVM uses “==” reference equality to identity the duplicate key
For Example:

identityHashMap m = new identityHashMap();
Integer I1 = new Integer(10);
Integer I2 = new Integer(10);
m.put(I1,”Xadmin”);
m.put(I2,”Ashish”);
System.out.println(m);

Here, Duplicate key is the identity by the reference equality as I1==I2 is false so No duplicate key has been entered I1and I2 are different key here.

Q28. What is the syntax to declare the IdentityHashMap class?
Ans:
Syntax to declare the IdentityHashMap class:
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Serializable, Cloneable

Q29. What are the constructors of the IdentityHashMap class?
Ans:
Constructor for the IdentityHashMap class

  • IdentityHashMap(): This constructor constructs a new, empty identity hash map with a default. It maximum size it 21.
  • IdentityHashMap(int expectedMaxSize): This constructs a new, empy identityHashMap with the specified expected maximus size.
  • IdentityHashMap(Map m): This construct a new IdentityHashMap with containing key-value pair mapping Map

Q30. What do you know about the WeakHashMap class in Java?
Ans:
WeakHashMap is an implementation of the Map interface. It stores weak references to its keys. It help a key-value pair to be garbage-collected. WeakHashMap is useful in implementing “registry-like” data structure.

Q31. Write a Sample program for the WeakHashMap class in Java?
Ans:

WeakHashMap w= new WeakHashMap();
Integer I1 = new Integer(10); 
w.put(I1,”Xadmin”);
System.out.println(w);
I1 = null;    // I1 is eligibale for garbage collector
System.gc();  // Garbage collector is called
Thread.sleep(5000);
System.out.println(w); // key is destroyed by GC

Output: {10,”Xadmin”}
{ }

Q32. Point out the difference between WaekHashMap and HashMap?
Ans:
WeakHashMap is similar to the HashMap except for the following difference. In the case of HashMap even though the object doesn’t have any reference. It is not eligible for GC. If it is associated with HashMap that means HashMap dominant Garbage collection. But in case of WeakHashMap, if the object doesn’t contain any reference it is eligible for GC even though an object associated with WeakHashMap that means that Garbage Collector dominate WeakHashMap.

Q33. What is the constructor of the WeakHashMap?
Ans:
Constructor of the WeakHashMap:

  • WeakHashMap(): This constructs a new, empty WeakHashMap with initial default capacity as 16 and default load factor as 0.75 percent.
  • WeakHashMap( int initialCapacity): This constructs a new empty WeakHashMap with given initial capacity.
  • WeakHashMap( int initialCapacity, float load_Factor): This constructs a new empty WeakHashMap with given initial capacity and a given load factor value.
  • WeakHashMap( Map m): This constructs a new WeakHashMap with the specified map.

Q34. What is SortedMap in Java?
Ans:
This is child interface of the Map. If we want to represent a group of key-value pair according to some sorting order of keys then we should go for SortedMap.

Q35. In SortedMap sorting is done on which based key or value-based?
Ans:
Sorting is based on the key not based on value.

Q36. What are the methods of the SortedMap in java?
Ans:

Methods

Description

Comparator comparator() This method returns the invoking sorted map comparator. It returns null if natural ordering is used for invoking map.
Object firstkey() This method returns the first key in the invoking map.
SortedMap headMap(Object end) This method returns a sorted map for those map entries with keys that are less then end
Object lastKey() Returns the last key.
SortedMap subMap(Object start, Object end) This method returns a map containing those entries with keys that are greater than or equal to start and less than an end
SortedMap tailMap(Object start) This method returns a map containing those entries with keys that are greater than or equal to start.

Q37. What is TreeMap in java?
Ans:
TreeMap class is implemented from the map interface. It is a red-black tree-based implementation. It provides an efficient means of storing key-value pairs in sorted order.

Q38. What are the properties of the TreeMap?
Ans: The properties for the TreeMap are listed below:

  • TreeMap class stores the value in key-value pair.
  • It contains only unique elements.
  • TreeMap cannot contain null as key but can have multiple null values.
  • TreeMap is non-synchronized.
  • TreeMap maintains an ascending order.
  • Duplicate key not allowed but a value can be duplicated
  • key should be homogenous type but a value can be a heterogeneous type

Q39. What is the Syntax to declare the TreeMap class in java?
Ans:
Syntax to declare the TreeMap class in java
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable

Q40. Explain the concept of the storing null in TreeMap till 1.6 version of Java?
Ans:
Null acceptance of TreeMap

  • If already some element is present in the table of TreeMap and then we try to enter null as key the Runtime error will occur saying NullPointerException.
  • If TreeMap is empty and we try to enter the null as key in TreeMap then it fine we can store the value of key as null now, if any other key-value entered the Runtime error with saying NullPointerException.

Q41. Explain the Concept of storing null in TreeMap onwards 1.7 v of Java
Ans: Null acceptance of TreeMap
Null not allowed after 1.7 v of java for a key on TreeMap. But null is allowed for value on multiple times.

Q42. What is the constructor of the TreeMap in Java?
Ans:
Constructor of TreeMap class

  • TreeMap(): This is used to construct an empty treemap with natural sorting order of its key.
  • TreeMap(Comparator<? Super K> comparator): it is used to construct an empty tree-based map with sorting using the comparator comp.
  • TreeMap(Map<? extends K, ? extends V>m): This constructor is used to initialize a treemap with the entries form m. Store natural storing order.
  • TreeMap(SortedMap<? extends K, ? extends V>m): This constructor is used to initialize a treemap with the entries form SortedMap map. Storing order will be same as the map.

Q43. What is HashTable in Java?
Ans:
HashTable class implements a hashtable, it stores the element in key-value pair. It inherits Dictionary class and implements the Map interface.

Q44. What are the properties of the HashTable class in Java?
Ans:
The main point of the Hashtable is listed below:

  • It contains unique elements.
  • It is a synchronized class
  • The default capacity of the Hashtable class is 11 and loadFactor is 0.75 percent.

Q45. What is Bucket in the collection in Java?
Ans: A HashTable is an array of a list. Each list present in HashTable is known as a bucket. The position of the bucket is identified by calling the hashcode() method. It contains values based on the key.

Q46. Do HashTable allowed null as key or value?
Ans:
HashTable class doesn’t allow null as key or value.

Q47. What is the syntax for HashTable in Java?
Ans: Syntax for HashTable class in Java
public class HashTable<K,V> extends Dictionary<K,V> implements Map<K,V>, cloneable, Serializable

Q48. What is the constructor of the HashTable in java?
Ans:
Constructor of the Hashtable class

  • Hashtable(): This constructor creates an empty hashtable.
  • Hashtable(int capacity): This construct a new, empty Hashtable with a specified initial capacity
  • Hashtable(int capacity, float loadFactor): This is used to construct a Hashtable with specified capacity and loadFactor.
  • Hashtable(Map m): This creates Hashtable with a specified map.

Q49. What is Properties class in Java
Ans:
The properties class object contains key and value pair both as String. This class is the subclass of Hashtable. In properties class, we write things which are changeable. In our program , which are changing frequently like (Username, mobile no, mail id etc) are not recommended to hard code in the java program because if there is any change then we have to recompile, rebuild, and redeploy the application even something restarting the server is also required which can create a big business impact to the client.

We can overcome this problem by using the properties file. We have to configure the variable properties in the properties file. We have to only read the variables of the properties file from the java program.

Q50. What is the constructor of the properties file?
Ans:
Constructor of the properties file

  • Properties(): This constructor creates an empty property list with no default value.
  • Properties(Properties default): It creates an empty property list with the specified defaults.

Q51. What are the methods of the properties class?
Ans: Methods of Properties class

  • public void load(Reader r): This method loads data from the Reader object.
  • public void load( inputStream s): This loads data from the input stream object.
  • public void load(InputStream is): This method used to load all of the properties represented by the XML document on the specified input stream into this properties table.
  • public String getProperty(String key): This method return value based on the key.
  • public void setProperty(String key, String value): It calls the put method of Hashtable.
  • public void list(PrintStream out): It is used to print the property list out of the specified out stream.
  • public void list(PrintStream out): It is used to print the property list out of the specified out stream.

That’s all about Map Interface interview questions with answers from Core Java Interviews. I have covered almost everything as per my knowledge for both freshers and experienced with 0 to 5  years, so prepare well for the Java interview Questions, I suggest you take a look at more Java Programming Interview Questions with answers on different topics of the core java posted in this xadmin website. Keep Learning!  All the Best!