如何将多个值存储到一个键(java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7351083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store several values to one key (java)
提问by Stephan
I search for a datastructure, where I can store several key-value pairs.
我搜索一个数据结构,我可以在其中存储多个键值对。
The data essentially looks like this:
数据基本上是这样的:
(1 , value_1)
(2 , value_2)
So I thought of using HashMap. Sadly this won't work for me, because multiple values to one key can occur.
于是想到了使用HashMap。遗憾的是,这对我不起作用,因为可能会出现一个键的多个值。
(In the example above:
(在上面的例子中:
(1 , value_2)
might be another entry )
可能是另一个条目)
Is there any way of performantly storing this data, except creating a List with a new Object or something like this.
有什么方法可以高效地存储这些数据,除了用新对象或类似的东西创建一个列表。
get(1)
should return value_1 and value_2 as a list or set or anything similar.
应该返回 value_1 和 value_2 作为列表或集合或任何类似的东西。
Thanks in advance
提前致谢
回答by Kevin
I think the data strucure you're looking for is in google's guava library, MultiMap. See http://guava-libraries.googlecode.com/svn-history/r13/trunk/javadoc/com/google/common/collect/Multimap.html.
我认为您正在寻找的数据结构位于谷歌的番石榴库 MultiMap 中。请参阅http://guava-libraries.googlecode.com/svn-history/r13/trunk/javadoc/com/google/common/collect/Multimap.html。
Basically it's a Map<K,Collection<V>>
but with an easier to use interface.
基本上它是一个Map<K,Collection<V>>
更易于使用的界面。
回答by Jiri Kriz
If the keys are integers and the values are e.g. strings, and the values belonging to one key are different, you could use e.g. the plain Java structure:
如果键是整数而值是例如字符串,并且属于一个键的值不同,则可以使用例如纯 Java 结构:
Map<Integer, HashSet<String>> container = new HashMap<Integer, HashSet<String>>();
void add(Map<Integer, HashSet<String>> container, int key, String value) {
HashSet<String> values = container.get(key);
if (values == null) {
values = new HashSet<String>();
}
values.add(value);
container.put(key, values);
}
回答by NPE
You could use HashMap<Integer,Set<T>>
or HashMap<Integer,List<T>>
, where T
is the type of value_1
, value_2
etc.
你可以使用HashMap<Integer,Set<T>>
或HashMap<Integer,List<T>>
,其中T
是的类型value_1
,value_2
等等。
Basically, get
would do what you want out of the box. Adding elements is a little bit more cumbersome; you could write a short wrapper function to make it nicer.
基本上,get
可以立即执行您想要的操作。添加元素稍微麻烦一些;你可以写一个简短的包装函数来使它更好。