简体   繁体   中英

Storing multiple values with same key in 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!

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

For eg

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

May be the interviewer was looking to check if you know the 3rd party APIs or not. There are multiple APIs available to do this. Some of them can be found at http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

One option is every time you want to insert a record into the map, get the length of the String, salt then encrypt the size of the String to use as the key. BAM: you have a (fairly) unique retrievable key for each String without having to much around with String concatenation.

Just make sure you use a reversible encryption algorithm.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM