简体   繁体   English

在HashMap中使用相同的键存储多个值

[英]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? 今天我接受了一次采访,我的面试官问我如何在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. 她给了我这个例子 - >如果给我一个String列表,我想将String的长度存储为键,String本身作为值存储。

I gave her the following solution in how I will be using HashMap: 我给了她以下解决方案,我将如何使用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. 整数是String的长度,ArrayList将存储该特定长度的字符串。

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. 采访者说这是使用HashMap的一种方式,但还有另一种方法,我不需要ArrayList或任何其他数据结构。 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. 可能是面试官想要检查你是否知道第三方API。 There are multiple APIs available to do this. 有多个API可用于执行此操作。 Some of them can be found at http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and 其中一些可以在http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-和

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. 一个选项是每次要将记录插入到映射中时,获取String的长度,然后加密盐,然后加密要用作键的String的大小。 BAM: you have a (fairly) unique retrievable key for each String without having to much around with String concatenation. BAM:你有一个(相当)唯一的可检索键,每个字符串都没有多少字符串连接。

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 uuid = UUID.randomUUID()
String key = stringSize + "," + uuid;

This will also result in a unique value that you can retrieve later using String.split(); 这也将导致一个唯一的值,您可以稍后使用String.split();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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