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,


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,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.