Saving multiple values ​​with the same key in HashMap

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

I gave her the following solution on how I will use the HashMap:

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

An integer that is the length of the string, and an ArrayList will store the strings of the appropriate length.

The interviewer said that this is one way to use HashMap, but there is another way that I will not need an ArrayList or any other data structure. During the interview, I could not come up with any solution, and now, after a sufficient search on Google, I still have nothing. Can someone tell me how I can achieve a solution to this issue?

Thanks!

+6
source share
3 answers

One way without using ANY DATA STRUCTURE is to combine all the rows in the values.

For instance,

 map.put(2,"rr*tt*yy"); map.put(3,"nnn*ggg*sss"); map.put(4,"ffff*dddd*jjjj"); 
+8
source

Perhaps the interviewer should check to see if you know third-party APIs or not. Several APIs are available for this. Some of them can be found at http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

0
source

One option is every time you want to insert an entry into the card, get the length of the string, then salt, then encrypt the size of the string to use as a key. BAM: you have a (fairly) unique recoverable key for each row without the need for much with a concatenation string.

Just make sure you use a reversible encryption algorithm.

Another option would be to generate a UUID and concatenate the string size.

 UUID uuid = UUID.randomUUID() String key = stringSize + "," + uuid; 

This will also result in a unique value that you can get later using String.split ();

0
source

Source: https://habr.com/ru/post/971404/


All Articles