Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing multiple values with same key in HashMap

Tags:

java

hashmap

I had an interview today and my interviewer asked me that how can I store multiple values having the same key in HashMap? She gave me this example-->If I am given a list of String and I am suppose to store the length of String as key and the String itself as value.

I gave her the following solution in how I will be using HashMap:

Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();

Integer being the length of the String and the ArrayList will store the Strings of that particular length.

The interviewer said that this is one way of using the HashMap but there is another way in which I won't be requiring ArrayList or any other data structure. During interview, I couldn't come up with any solution and now after enough googling, I still have nothing. Can anyone tell me how can I achieve the solution to this question?

Thanks!

like image 419
Shrikant Kakani Avatar asked Jun 27 '14 06:06

Shrikant Kakani


People also ask

Can a HashMap store multiple values for same key?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

What happen if we add same key with different values to HashMap?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How HashMap store duplicate values?

Let's see how to store our multiple values into an ArrayList, which retains duplicates: MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); map. put("key1", "value1"); map. put("key1", "value2"); map.


1 Answers

One way without using ANY DATA STRUCTURE is concatenating all strings in values.

For e.g.

map.put(2,"rr*tt*yy");
map.put(3,"nnn*ggg*sss");
map.put(4,"ffff*dddd*jjjj");
like image 151
Ninad Pingale Avatar answered Sep 30 '22 12:09

Ninad Pingale