DEV Community

Cover image for How to Work with HashMap in Java
Himanshu Singh Tomar
Himanshu Singh Tomar

Posted on

How to Work with HashMap in Java

HashMap is a powerful data structure in Java that allows you to store and manage key-value pairs efficiently. This guide will cover the basics of working with HashMap, including commonly used methods and examples to help you understand its usage.


Introduction to HashMap

A HashMap stores data in the form of key-value pairs and provides constant-time complexity for basic operations like put, get, and remove (on average). Here's why HashMap is so useful:

  • Keys are unique, but values can be duplicated.
  • Keys and values can be of any object type.
  • It is part of the java.util package.
  • It allows null as a key or value.

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();

        // Adding key-value pairs
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        // Accessing a value
        System.out.println(map.get(1)); // Output: Apple
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating a HashMap

To create a HashMap, use the following syntax:

HashMap<KeyType, ValueType> mapName = new HashMap<>();
Enter fullscreen mode Exit fullscreen mode

Example:

HashMap<String, Integer> frequencyMap = new HashMap<>();
Enter fullscreen mode Exit fullscreen mode

Here, the key type is String and the value type is Integer.


Commonly Used Methods

Here are the key methods of HashMap:

1. put(K key, V value)

  • Description: Adds a key-value pair to the map. If the key already exists, it updates the value.
  • Example:
  HashMap<Integer, String> map = new HashMap<>();
  map.put(1, "Apple");
  map.put(2, "Banana");
  map.put(1, "Cherry"); // Updates value for key 1
  System.out.println(map); // Output: {1=Cherry, 2=Banana}
Enter fullscreen mode Exit fullscreen mode

2. get(Object key)

  • Description: Retrieves the value associated with the specified key. Returns null if the key is not found.
  • Example:
  System.out.println(map.get(1)); // Output: Cherry
  System.out.println(map.get(3)); // Output: null
Enter fullscreen mode Exit fullscreen mode

3. getOrDefault(Object key, V defaultValue)

  • Description: Retrieves the value for the specified key. Returns defaultValue if the key is not found.
  • Example:
  System.out.println(map.getOrDefault(3, "Default")); // Output: Default
Enter fullscreen mode Exit fullscreen mode

4. containsKey(Object key)

  • Description: Checks if the map contains the specified key.
  • Example:
  System.out.println(map.containsKey(1)); // Output: true
  System.out.println(map.containsKey(3)); // Output: false
Enter fullscreen mode Exit fullscreen mode

5. containsValue(Object value)

  • Description: Checks if the map contains the specified value.
  • Example:
  System.out.println(map.containsValue("Cherry")); // Output: true
  System.out.println(map.containsValue("Orange")); // Output: false
Enter fullscreen mode Exit fullscreen mode

6. remove(Object key)

  • Description: Removes the entry for the specified key and returns the value. Returns null if the key is not found.
  • Example:
  System.out.println(map.remove(1)); // Output: Cherry
  System.out.println(map); // Output: {2=Banana}
Enter fullscreen mode Exit fullscreen mode

7. putIfAbsent(K key, V value)

  • Description: Adds a key-value pair only if the key is not already present in the map.
  • Example:
  map.putIfAbsent(3, "Orange");
  System.out.println(map); // Output: {2=Banana, 3=Orange}
Enter fullscreen mode Exit fullscreen mode

8. replace(K key, V value)

  • Description: Replaces the value associated with the key, only if the key exists.
  • Example:
  map.replace(3, "Grapes");
  System.out.println(map); // Output: {2=Banana, 3=Grapes}
Enter fullscreen mode Exit fullscreen mode

9. keySet()

  • Description: Returns a Set containing all the keys in the map.
  • Example:
  System.out.println(map.keySet()); // Output: [2, 3]
Enter fullscreen mode Exit fullscreen mode

10. values()

  • Description: Returns a Collection of all the values in the map.
  • Example:
  System.out.println(map.values()); // Output: [Banana, Grapes]
Enter fullscreen mode Exit fullscreen mode

11. entrySet()

  • Description: Returns a Set of all key-value pairs (Map.Entry) in the map.
  • Example:
  for (var entry : map.entrySet()) {
      System.out.println(entry.getKey() + " -> " + entry.getValue());
  }
  // Output:
  // 2 -> Banana
  // 3 -> Grapes
Enter fullscreen mode Exit fullscreen mode

12. compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

  • Description: Updates the value for the given key using a computation function.
  • Example:
  map.put(1, 10);
  map.compute(1, (k, v) -> v * 2); // Doubles the value
  System.out.println(map); // Output: {1=20}
Enter fullscreen mode Exit fullscreen mode

13. merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

  • Description: Combines a new value with the existing value for the given key.
  • Example:
  map.put(1, 10);
  map.merge(1, 5, Integer::sum); // Adds the values
  System.out.println(map); // Output: {1=15}
Enter fullscreen mode Exit fullscreen mode

Full Example: Word Frequency Counter

Here is a complete example that demonstrates how to use HashMap to count the frequency of words:

import java.util.HashMap;

public class WordFrequency {
    public static void main(String[] args) {
        String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};
        HashMap<String, Integer> frequencyMap = new HashMap<>();

        for (String word : words) {
            frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);
        }

        System.out.println(frequencyMap); // Output: {orange=1, banana=2, apple=3}
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The HashMap class is a versatile and efficient way to manage key-value pairs in Java. By understanding its methods, you can solve a wide range of problems, from simple lookups to complex data manipulations. Start using HashMap in your projects to leverage its power!

Top comments (0)