问题
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)
should return value_1 and value_2 as a list or set or anything similar.
Thanks in advance
回答1:
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.
回答2:
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);
}
回答3:
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.
来源:https://stackoverflow.com/questions/7351083/how-to-store-several-values-to-one-key-java