Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

should return value_1 and value_2 as a list or set or anything similar.

Thanks in advance

like image 668
Stephan Avatar asked Dec 22 '22 09:12

Stephan


2 Answers

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.

like image 100
Kevin Avatar answered Jan 08 '23 17:01

Kevin


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);
}
like image 27
Jiri Kriz Avatar answered Jan 08 '23 15:01

Jiri Kriz