Java: Creating HashMap by Associating Multiple Values with Same Key

In this article, we will see how we can create a HashMap with multiple values associated with the same Key in Java. For example, we want to keep the track of strings and their occurrences in the text.

Like

  • “a” is present at following indexes 4, 11, 25, 39
  • “an” is present at the following indexes 36, 49, 63, 77
  • “the” is present at the following indexes 14, 27, 43, 89

To store this data in a lookup table, we have to create a HashMap with a key as a string and then associate multiple values with the same key.

HashMap with List<T> Object as Value

To Create a HashMap of the key as String List Of integers as Value
HashMap<String, List<Integer>> wordFreqMap = new HashMap<>();

The below code is the implementation for that.

// Program :

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MultipleValuesListExample {
    public static void main(String[] args) {
        // A HashMap created where key as String List Of integers as Value
        HashMap<String, List<Integer>> wordFreqMap = new HashMap<>();
        // An array Of Occurrences is created
        Integer[] occurences = { 4, 11, 25, 39 };
        // Adding List as value in the map
        wordFreqMap.put("a", Arrays.asList(occurences));
        // Adding List as value in the map
        wordFreqMap.put("an", Arrays.asList(new Integer[] { 36, 49, 63, 77 }));
        // Adding List as value in the map
        wordFreqMap.put("the", Arrays.asList(new Integer[] { 14, 27, 43, 89 }));
        // Printing the Map Contents
        System.out.println(wordFreqMap);
    }
}
Output :
{a=[4, 11, 25, 39], an=[36, 49, 63, 77], the=[14, 27, 43, 89 ]}

Also, See:

HashMap with TreeSet as Value

To create a HashMap of a key as String List Of integers as Value
HashMap<String, TreeSet<Integer>> wordFreqMap = new HashMap<>();

The below code is the implementation for that.

// Program :
import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeSet;
public class MultipleValuesSetExample 
{
    public static void main(String[] args) 
    {
        // A HashMap created where key as String List Of integers as Value
        HashMap<String, TreeSet<Integer>> wordFreqMap = new HashMap<>();
        // An array Of Occurrences created
        Integer[] occurences = { 4, 11, 25, 39 };
        // Adding TreeSet as value in the map
        wordFreqMap.put("a", new TreeSet<Integer>(Arrays.asList(occurences)));
        // Adding TreeSet as value in the map
        wordFreqMap.put("an", new TreeSet<Integer>(Arrays.asList(new Integer[] { 36, 49, 63, 77 })));
        // Adding TreeSet as value in the map
        wordFreqMap.put("the", new TreeSet<Integer>(Arrays.asList(new Integer[] { 14, 27, 43, 89 })));
        // Printing the Map Contents
        System.out.println(wordFreqMap);
    }
}
Output :
{a=[4, 11, 25, 39], an=[36, 49, 63, 77], the=[14, 27, 43, 89 ]}