Java Language – 28 – Maps (HashMap, TreeMap, etc.)

Collections and Data Structures – Maps (HashMap, TreeMap, etc.)
Introduction

Maps are fundamental data structures in Java that allow you to store and retrieve data in key-value pairs. Java provides several map implementations, including ‘HashMap’ and ‘TreeMap.’ In this guide, we’ll delve into the world of maps in Java, explore the differences between ‘HashMap’ and ‘TreeMap,’ and learn how to effectively use them in your Java applications.

HashMap: Unordered Key-Value Pairs

‘HashMap’ is an implementation of the ‘Map’ interface in Java. It stores key-value pairs in an unordered manner, offering fast performance for basic operations like ‘put,’ ‘get,’ and ‘remove.’ Duplicate keys are not allowed, but duplicate values are permitted.

Example – Using HashMap

Let’s see an example of creating and using a ‘HashMap’ to store a mapping of names to their ages:


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

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

        // Adding key-value pairs to the HashMap
        ageMap.put("Alice", 28);
        ageMap.put("Bob", 32);
        ageMap.put("Charlie", 25);

        // Retrieving the age for a specific name
        int aliceAge = ageMap.get("Alice");
        System.out.println("Alice's age is " + aliceAge);
    }
}

In this example, we create a ‘HashMap’ to map names to their ages. You can quickly retrieve the age of a person by providing their name.

TreeMap: Sorted Key-Value Pairs

‘TreeMap’ is another map implementation in Java that stores key-value pairs in sorted order. It uses a Red-Black Tree internally to maintain the keys in ascending order. ‘TreeMap’ does not allow duplicate keys.

Example – Using TreeMap

Here’s an example of creating and using a ‘TreeMap’ to store a mapping of cities to their populations:


import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        Map<String, Integer> populationMap = new TreeMap<>();

        // Adding key-value pairs to the TreeMap
        populationMap.put("New York", 8398748);
        populationMap.put("Los Angeles", 3990456);
        populationMap.put("Chicago", 2705994);

        // Retrieving the population of a specific city
        int newYorkPopulation = populationMap.get("New York");
        System.out.println("New York's population is " + newYorkPopulation);
    }
}

In this example, we create a ‘TreeMap’ to map cities to their populations. The keys (city names) are automatically sorted in ascending order, making it easy to find information about a specific city.

Choosing Between HashMap and TreeMap

The choice between ‘HashMap’ and ‘TreeMap’ depends on your application’s requirements:

  • ‘HashMap’ is a better choice when:
    • You need fast key-value lookups and don’t require sorting by keys.
    • You can tolerate a lack of specific key order.
    • Duplicate values are acceptable.
  • ‘TreeMap’ is a better choice when:
    • You require keys to be sorted in ascending or descending order.
    • You need to find the nearest key in a range of keys efficiently.
    • Duplicate keys are not allowed.
Common Map Operations

Maps provide several common operations for managing key-value pairs:

  • Adding Key-Value Pairs: Use the ‘put’ method to add key-value pairs to the map. If the key already exists, the value is updated.
  • Retrieving Values: Use the ‘get’ method to retrieve the value associated with a specific key.
  • Removing Key-Value Pairs: Use the ‘remove’ method to delete key-value pairs based on the key.
  • Iterating: Use ‘for-each’ loops or iterators to traverse the map, either keys, values, or key-value pairs.
Conclusion

Maps are vital for storing and retrieving data efficiently in key-value pairs. ‘HashMap’ and ‘TreeMap’ are two prominent implementations, each offering unique advantages. By understanding their characteristics and use cases, you can make informed decisions about which map suits your Java application’s needs.