Sunday, June 4, 2023

40 Java HashMap Interview Questions and Answers for 2 to 3 Years Experienced

Here are 40 Java HashMap interview questions and answers suitable for candidates with 2 to 3 years of experience:


1. What is a HashMap in Java?

HashMap is a data structure that stores key-value pairs in Java. It implements the Map interface and uses hashing to store and retrieve elements efficiently. 

2. How do you create a HashMap in Java?

You can create a HashMap using the HashMap class and the new keyword:

Map hashMap = new HashMap<>();

3. How do you add elements to a HashMap?

You can add elements to a HashMap using the put() method:

hashMap.put(key, value);

4. How do you retrieve a value from a HashMap?

You can retrieve a value from a HashMap using the get() method:

ValueType value = hashMap.get(key);
5. How do you check if a key exists in a HashMap?

You can check if a key exists in a HashMap using the containsKey() method:

boolean containsKey = hashMap.containsKey(key);

6. How do you check if a value exists in a HashMap?

You can check if a value exists in a HashMap using the containsValue() method:


boolean containsValue = hashMap.containsValue(value);

7. How do you remove an element from a HashMap?

You can remove an element from a HashMap using the remove() method:


ValueType removedValue = hashMap.remove(key);
8. How do you get the number of elements in a HashMap?

You can get the number of elements in a HashMap using the size() method:


int size = hashMap.size();

9. How do you iterate over a HashMap?

You can iterate over a HashMap using various methods such as keySet(), entrySet(), or forEach():


// Using keySet()
for (KeyType key : hashMap.keySet()) {
    ValueType value = hashMap.get(key);
    // Perform operations with key-value pair
}

// Using entrySet()
for (Map.Entry entry : hashMap.entrySet()) {
    KeyType key = entry.getKey();
    ValueType value = entry.getValue();
    // Perform operations with key-value pair
}

// Using forEach()
hashMap.forEach((key, value) -> {
    // Perform operations with key-value pair
});

10. What happens if two keys have the same hash code in a HashMap? 

If two keys have the same hash code, a collision occurs. 

In a HashMap, collisions are resolved by chaining the elements in a linked list at the corresponding index. 


11. How does HashMap handle hash code collisions? 

HashMap handles hash code collisions by storing the colliding elements in a linked list at the corresponding index. 

Each element in the list contains the key-value pair.


12. What is the difference between HashMap and HashTable?

The main differences are: 

HashMap is not thread-safe, while HashTable is thread-safe. 

HashMap allows null keys and values, while HashTable does not allow null keys or values. 

HashMap is faster than HashTable.


13. How do you sort a HashMap by its keys?

You can sort a HashMap by its keys by converting it to a TreeMap, which automatically sorts the keys:


Map sortedMap = new TreeMap<>(hashMap);

14. How do you sort a HashMap by its values?

You can sort a HashMap by its values by creating a list of entries and sorting the list using a custom comparator:


List> entryList = new ArrayList<>(hashMap.entrySet());
entryList.sort(Map.Entry.comparingByValue());

15. What is the load factor in a HashMap?

The load factor is a measure of how full the HashMap is allowed to get before its capacity is automatically increased. It affects the performance and space efficiency of the HashMap.


16. What is the default load factor of a HashMap?

The default load factor of a HashMap is 0.75. This means that the HashMap can reach 75% of its capacity before it is resized.


17. How does the initial capacity and load factor affect the performance of a HashMap?

Choosing an appropriate initial capacity and load factor can improve the performance of a HashMap. A larger initial capacity reduces the number of rehashing and resizing operations, while a smaller load factor increases the number of elements that can be stored before resizing.


18. How do you increase the capacity of a HashMap?

The capacity of a HashMap is automatically increased when the number of elements exceeds the product of the load factor and the current capacity. You don't need to manually increase the capacity.


19. What happens if the initial capacity of a HashMap is too low?

If the initial capacity is too low, the HashMap may need to be resized frequently, resulting in performance degradation. It is recommended to provide an initial capacity that accommodates the expected number of elements.


20. How do you retrieve all the keys from a HashMap?

You can retrieve all the keys from a HashMap using the keySet() method:


Set keys = hashMap.keySet();

21. How do you retrieve all the values from a HashMap?

You can retrieve all the values from a HashMap using the values() method:


Collection values = hashMap.values();

22. How do you check if a HashMap is empty?

You can check if a HashMap is empty using the isEmpty() method:


boolean isEmpty = hashMap.isEmpty();

23. Can you use objects of custom classes as keys in a HashMap?

Yes, you can use objects of custom classes as keys in a HashMap. For this to work correctly, you need to override the hashCode() and equals() methods in your custom class.


24. Why is it important to override the hashCode() and equals() methods for objects used as keys in a HashMap?

Overriding the hashCode() and equals() methods ensures that the keys are compared correctly and that the elements are stored and retrieved from the HashMap accurately.


25. Can a HashMap contain duplicate values?

Yes, a HashMap can contain duplicate values. However, each key in a HashMap must be unique.


26. Can a HashMap contain null keys?

Yes, a HashMap can contain a single null key. However, it can contain multiple null values.


27. Can a HashMap contain null values?

Yes, a HashMap can contain multiple null values. However, it can contain only a single null key.


28. How do you copy the contents of one HashMap to another?

You can copy the contents of one HashMap to another using the putAll() method:


Map newHashMap = new HashMap<>();
newHashMap.putAll(hashMap);


29. What happens if you add a duplicate key to a HashMap?

If you add a duplicate key to a HashMap, the new value replaces the existing value associated with that key.


30. How do you replace a value for a given key in a HashMap?

You can replace a value for a given key in a HashMap using the put() method:


hashMap.put(key, newValue);

31. How do you replace a value in a HashMap only if the key exists?

You can replace a value in a HashMap only if the key exists using the replace() method:


ValueType replacedValue = hashMap.replace(key, newValue);


32. How do you replace a value in a HashMap only if the key and value match the existing entry?

You can replace a value in a HashMap only if the key and value match the existing entry using the replace() method:


boolean replaced = hashMap.replace(key, oldValue, newValue);


33. How do you remove all the elements from a HashMap?

You can remove all the elements from a HashMap using the clear() method:


hashMap.clear();


34. What is the difference between HashMap and LinkedHashMap?

The main difference is that LinkedHashMap maintains the insertion order of elements, while HashMap does not guarantee any specific order.


35. What is the difference between HashMap and TreeMap?

The main difference is that TreeMap sorts the elements based on their natural ordering or a custom comparator, while HashMap does not maintain any specific order.


36 How do you make a HashMap thread-safe?

You can make a HashMap thread-safe by using the ConcurrentHashMap class instead of HashMap. ConcurrentHashMap provides built-in thread-safety and concurrent access.


37. What is the time complexity of operations in a HashMap?

The time complexity of operations in a HashMap is generally O(1) on average, including put(), get(), containsKey(), and remove(). However, in the worst case scenario with many collisions, the time complexity can approach O(n), where n is the number of elements in the HashMap.


38. When should you use a HashMap over other data structures?

You should use a HashMap when you need a fast and efficient way to store and retrieve key-value pairs and when the order of elements is not important.


39. Can two threads simultaneously modify a HashMap?

In a standard HashMap, two threads modifying the HashMap simultaneously can result in an inconsistent state and data loss. To handle concurrent modifications, you can use ConcurrentHashMap or synchronize the access to the HashMap using external synchronization.

40. How does HashMap work internally?

HashMap uses an array of linked lists (buckets) and a hash function to store and retrieve elements. The hash code of the key determines the index in the array, and collisions are resolved by chaining elements in the linked lists. 

12 Examples of ConcurrentHashMap in Java? put, get, containsKey, containsValue, kyeSet, replace, and remove Examples

Sure! Here are 12 examples demonstrating various operations with ConcurrentHashMap in Java, including put(), get(), containsKey(), containsValue(), keySet(), replace(), and remove(): 

1. Creating a ConcurrentHashMap:


import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap
        ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();
    }
}


2. Adding key-value pairs using put():


concurrentHashMap.put("Key1", 1);
concurrentHashMap.put("Key2", 2);
concurrentHashMap.put("Key3", 3);

3. Retrieving a value using get():


int value = concurrentHashMap.get("Key1");
System.out.println("Value: " + value);

4. Checking if a key exists using containsKey():


boolean containsKey = concurrentHashMap.containsKey("Key2");
System.out.println("Contains Key: " + containsKey);

5. Checking if a value exists using containsValue():


boolean containsValue = concurrentHashMap.containsValue(3);
System.out.println("Contains Value: " + containsValue);

6. Getting the set of keys using keySet():


Set keySet = concurrentHashMap.keySet();
System.out.println("Key Set: " + keySet);

7. Replacing a value for a given key using replace():


concurrentHashMap.replace("Key1", 10);

8. Removing a key-value pair using remove():


concurrentHashMap.remove("Key2");

9. Removing a key-value pair if the key-value pair exists using remove():


concurrentHashMap.remove("Key3", 3);

10. Removing a key-value pair only if the key-value pair matches the existing entry using remove():


concurrentHashMap.remove("Key1", 5);

11.Iterating over the key-value pairs using a for-each loop:


for (Map.Entry entry : concurrentHashMap.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ": " + value);
}

12. concurrentHashMap.clear();


concurrentHashMap.clear();

These examples demonstrate various operations you can perform on a ConcurrentHashMap in Java. Feel free to modify and combine them to suit your specific needs.

Java HashMap ContainsKey and ContainsValue Example - How to check if a Key Exists in Map?

To check if a key exists in a HashMap in Java, you can use the containsKey() method. Similarly, to check if a value exists in a HashMap, you can use the containsValue() method. 

Here's an example that demonstrates both scenarios:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map hashMap = new HashMap<>();

        // Adding key-value pairs to the HashMap
        hashMap.put("Key1", 1);
        hashMap.put("Key2", 2);
        hashMap.put("Key3", 3);

        // Checking if a key exists using containsKey()
        String keyToCheck = "Key2";
        if (hashMap.containsKey(keyToCheck)) {
            System.out.println("The key '" + keyToCheck + "' exists in the HashMap.");
        } else {
            System.out.println("The key '" + keyToCheck + "' does not exist in the HashMap.");
        }

        // Checking if a value exists using containsValue()
        int valueToCheck = 3;
        if (hashMap.containsValue(valueToCheck)) {
            System.out.println("The value " + valueToCheck + " exists in the HashMap.");
        } else {
            System.out.println("The value " + valueToCheck + " does not exist in the HashMap.");
        }
    }
}

In this example, we create a HashMap called hashMap and add three key-value pairs using the put() method. Then, we demonstrate how to check if a key exists using the containsKey() method. We specify the key to check in the keyToCheck variable. If the key exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed. 

Next, we show how to check if a value exists in the HashMap using the containsValue() method. We specify the value to check in the valueToCheck variable. If the value exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed. 

The output of this example will be:


The key 'Key2' exists in the HashMap.
The value 3 exists in the HashMap.

As you can see, the program correctly identifies that the key "Key2" exists in the HashMap, and the value 3 also exists in the HashMap.

How to Merge two HashMap in Java 8 - Map.merge() example Tutorial

In Java 8, you can use the merge() method provided by the Map interface to merge two HashMaps. The merge() method allows you to specify a merging function that determines how conflicting values for the same key should be resolved. 

Here's an example:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating two HashMaps
        Map map1 = new HashMap<>();
        Map map2 = new HashMap<>();

        // Adding key-value pairs to map1
        map1.put("Key1", 1);
        map1.put("Key2", 2);

        // Adding key-value pairs to map2
        map2.put("Key2", 3);
        map2.put("Key3", 4);

        System.out.println("HashMap 1: " + map1);
        System.out.println("HashMap 2: " + map2);

        // Merging the two HashMaps using merge() and resolving conflicts with sum
        map2.forEach((key, value) -> map1.merge(key, value, Integer::sum));

        System.out.println("Merged HashMap: " + map1);
    }
}

In this example, we create two HashMaps: map1 and map2. We add key-value pairs to each map using the put() method. Then, we print the contents of both HashMaps. 

To merge the two HashMaps, we use the merge() method on map1 and pass map2 as an argument. We provide a lambda expression (key, value) -> map1.merge(key, value, Integer::sum) as the merging function. This lambda expression specifies that when a conflict occurs, the values should be summed.

The merge() method takes three arguments: the key, the value from the map2, and the merging function. It merges the key-value pairs from map2 into map1, applying the merging function to resolve conflicts. If the key already exists in map1, the merging function is called with the existing value and the new value, and the result is stored as the new value for the key. If the key is not present in map1, the key-value pair from map2 is added to map1 as is. 

Finally, we print the merged HashMap, map1. 

The output of this example will be:


HashMap 1: {Key1=1, Key2=2}
HashMap 2: {Key2=3, Key3=4}
Merged HashMap: {Key1=1, Key2=5, Key3=4}

As you can see, the values for the common key "Key2" are merged according to the specified merging function, which in this case is the sum of the values. The value for "Key2" becomes 5 in the merged HashMap.

How to update value for a given key in HashMap - Java 8 getOrDefault() example

In Java 8, you can use the getOrDefault() method in conjunction with the put() method to update the value for a given key in a HashMap. 

Here's an example:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map hashMap = new HashMap<>();

        // Adding initial key-value pairs
        hashMap.put("Key1", 1);
        hashMap.put("Key2", 2);
        hashMap.put("Key3", 3);

        System.out.println("HashMap before update: " + hashMap);

        // Updating the value for a given key using getOrDefault() and put()
        String keyToUpdate = "Key2";
        int newValue = 10;

        int oldValue = hashMap.getOrDefault(keyToUpdate, 0);
        hashMap.put(keyToUpdate, newValue);

        System.out.println("HashMap after update: " + hashMap);
    }
}

In this example, we create a HashMap called hashMap to store key-value pairs. We add three initial key-value pairs using the put() method. Then, we print the hashMap before the update. 

To update the value for a given key, we specify the key to update (keyToUpdate) and the new value (newValue). We use getOrDefault(key, defaultValue) to retrieve the current value associated with the key. If the key is present, it returns the current value; otherwise, it returns the specified default value (0 in this case). We store the old value in oldValue variable. 

Next, we use the put(key, value) method to update the value for the given key. We provide the keyToUpdate and newValue as arguments. If the key is already present in the map, the value will be updated; otherwise, a new key-value pair will be added. 

Finally, we print the updated hashMap. The output of this example will be:


HashMap before update: {Key1=1, Key2=2, Key3=3}
HashMap after update: {Key1=1, Key2=10, Key3=3}

As you can see, the value for the key "Key2" is updated from 2 to 10 in the HashMap.