In this article we will discuss how to create a HashMap with multiple values associated with same Key in Java.

Suppose we want to create a HashMap to keep the track of strings and their occurrences in text. For example.

“the” occurred at following indexes 1,4,8,12.
“at” occurred at following indexes 22, 28, 44 ,89
“from” occurred at following indexes 32, 39, 51, 73

To store this data in a lookup table / map , we need to create a HashMap with key as string and then associate multiple values with same key. We can do this by storing a List of Integers i.e. List<Integer> objects as values in HashMap.

HashMap with List<T> Object as Value

Let’s Create a HashMap of String as Key and List<Integer> as value i.e.

Now let’s push elements into this HashMap,

Complete example is as follows,

Output:

Idea behind associating Multiple values with same key is to store another Collection as Value in the HashMap. This can be a List or Set or any other Map too.

HashMap with TreeSet as Value

We can create a HashMap with TreeSet as Value too i.e.

Let’s change the above example and associate keys with TreeSet of Integers instead of List. It will store the Integers in Sorted Order. Checkout complete example as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.