Core Java

Multiple Values for a Single Key in HashMap

A HashMap is a data structure in Java that allows you to store key-value pairs. In a standard HashMap, each key is associated with a single value. However, there are circumstances where you might find it necessary to associate several values with a single key. In this guide, we will explore various methods and provide code examples for implementing a HashMap with multiple values for the same key in Java.

1. Why HashMap with Multiple Values?

Imagine building an application to manage some great authors and their works, and want to keep track of the books written by each author. Each author can have multiple books to their name, and we need a data structure to efficiently store this information.

A typical HashMap wouldn’t be adequate in this scenario because it associates only one value with each key. Below is an example code of multiple values per key in a HashMap Java problem:

public class MultipleValueHashMap {

    public static void main(String[] args) {
        
        HashMap authors = new HashMap();

        authors.put("charles", "A Tale of Two Cities");
        authors.put("chinua", "Things Fall Apart");
        
        //overwrites the value "A Tale of Two Cities" in the "charles" key
        authors.put("charles", "Great Expectations");

        //prints out "Great Expectations"
        System.out.println(authors.get("charles"));
        
        //prints out map
        System.out.println("" + authors);
        
    }
}

In the above code, the key charles is used twice making the second value overwrite the first.

To solve this problem, we can embed a Collection class such as an ArrayList or a Set within a HashMap or we can use Third-party libraries like Apache Commons Collections or Google Guava’s Collections.

2. Solution 1: Using Java Collections Framework

To create a HashMap with multiple values, we can use the Java Collections Framework. We can use a HashMap to store lists of values associated with each key as follows:

public class MultiValueHashMapExample {

    public static void main(String[] args) {
        Map<String, ArrayList<String>> multiValueMap = new HashMap<String, ArrayList<String>>();

        // Add values to the map
        multiValueMap.computeIfAbsent("Thomas", k -> new ArrayList<>()).add("The Age of Reason");
        multiValueMap.computeIfAbsent("Thomas", k -> new ArrayList<>()).add("Common Sense");
        
        // Adding values for another key
        multiValueMap.computeIfAbsent("Charles", k -> new ArrayList<>()).add("A Tale of Two Cities");
        multiValueMap.computeIfAbsent("Charles", k -> new ArrayList<>()).add("Great Expectations");

        // Retrieving values associated with a key
        List<String> thomasBooks = multiValueMap.get("Thomas");
        List<String> charlesBooks = multiValueMap.get("Charles");
        
        System.out.println("Thomas Books: " + thomasBooks);
        System.out.println("Charles Books: " + charlesBooks);
    }
}

In the above example, we use a HashMap with a key of type String and a value of type ArrayList<String>. Next, we use the computeIfAbsent method provided by the java.util.Map interface to compute new values for our keys if the keys are not already present in the map.

If the keys are already on the map, the computeIfAbsent method returns the existing value associated with the keys. When we access the key Thomas, and Charles, all of their associated values will be returned.

The output from running the above code is shown in Fig 1 below:

Fig 1: Output from running Multi Values from a Single Key in Hashmap using Collections Framework in Java
Fig 1: Output from running Multi Values from a Single Key in Hashmap using Collections Framework in Java

3. Solution 2: Using Third-party Libraries

To implement a HashMap with multiple values, we can also use third-party libraries that offer specialized data structures for this purpose. Examples of such library is the Guava Collections, which provides a ListMultimap interface or the Apache Commons Collections MultiMap.

3.1 Using Guava’s Collection

In Guava, we can add multiple values to a single key using the Multimap interface that is part of the Guava library’s collection framework. The most commonly used implementation is the ArrayListMultimap. To use the Guava collections in a Maven project, add the following entry to the POM:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version> <!-- Use the latest version -->
</dependency>

Now, with the POM updated, we can create a Multimap and add values to a single key like this:

public class MultiValuesMapExampleGuava {

    public static void main(String[] args) {
       // Create a Multimap using ArrayListMultimap
       
        Multimap<String, String> multimap = ArrayListMultimap.create();

        // Add values to a single key
        multimap.put("Charles", "Great Expectations");
        multimap.put("Charles", "Tale of Two Cities");

        // Add more values to a different key
        multimap.put("Thomas", "Age of Reason");
        multimap.put("Thomas", "Common Sense");

        // Retrieve values for a key
        System.out.println("Books by Charles: " + multimap.get("Charles"));
        System.out.println("Books by Thomas: " + multimap.get("Thomas"));
    }
}

In the above example, we create a Multimap using ArrayListMultimap, and then we add multiple values to the keys Charles and Thomas. The get method allows us to retrieve all values associated with a specific key.

When we run the above code, we should get the following output:

Books by Charles: [Great Expectations, Tale of Two Cities]
Books by Thomas: [Age of Reason, Common Sense]

3.2 Using Apache Commons Collection

Using the Apache Commons Collection, we can add multiple values to a single key. First, let’s add the library to our project if we are using Maven build by adding the following dependency to our pom.xml:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version> <!-- Use the latest version -->
        </dependency>

Now, with POM updated, we can create a Map with Lists as values in our class:

public class MultiValuesExampleApacheCommons {

    public static void main(String[] args) {
        MultiMap<String, String> multiValueMap = new MultiValueMap<String, String>();

        // Add values to a single key
        multiValueMap.put("berries", "Tomatoes");
        multiValueMap.put("berries", "Grapes");

        // Add more values to a different key
        multiValueMap.put("legumes", "Peanuts");
        multiValueMap.put("legumes", "Beans");

        // Print out Map with Multiple Values
        System.out.println("" + multiValueMap);
    }
}

In this example, we use the MultiMap from the Apache Commons Collections to create a map with List values. We then add multiple values to a single key using the put method. We can retrieve all values associated with a key using a get method like this:

        // Retrieve values for a key
        System.out.println("Values for Berries: " + multiValueMap.get("berries"));
        System.out.println("Values for Legumes: " + multiValueMap.get("legumes"));

Finally, we print out the values in our Map. The output from running the above code is:

{legumes=[Peanuts, Beans], berries=[Tomatoes, Grapes]}

It is important to note that the usage of Apache Commons Collections may change over time, and it is best to always check the latest documentation and version-specific information for the library you are using.

4. Conclusion

In this article, we delved into the idea of creating a HashMap that facilitates the association of multiple values with a single key. We showed code examples using the in-built Java Collections Framework and Third-party libraries such as Guava’s Collections and the Apache Commons Collections. Generally, HashMaps with multiple values for the same key offer an elegant solution for scenarios where one key needs to be associated with multiple values.

In conclusion, using a HashMap with multiple values for the same key in Java is a powerful technique that can enhance the efficiency of data management in our programs. By employing data structures like Map<String, List<String>> or leveraging libraries such as Guava’s Multimap and Apache Commons Collections Multimap , we can efficiently associate and retrieve multiple values for a single key.

5. Download the Source Code

This was an example of Multiple Values for a Single Key in a HashMap in Java.

Download
You can download the full source code of this example here: Multiple Values for a Single Key in a HashMap in Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button