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!
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With