How to store several values to one key (java)
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.
(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)开发者_如何学Go
should return value_1 and value_2 as a list or set or anything similar.
Thanks in advance
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.
Basically it's a Map<K,Collection<V>>
but with an easier to use interface.
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:
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);
}
You could use HashMap<Integer,Set<T>>
or HashMap<Integer,List<T>>
, where T
is the type of value_1
, value_2
etc.
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.
精彩评论