jayraynet
jayraynet

Reputation: 906

Is there a java collection that allows for a one-key-to-multiple-values relationship?

I have a need for a collection type that allows for a multiple values to be associated with multiple keys. Ideally, I would use it like Map, but map is intended for a given key to yield a single value.

Below is an example of how I would like to use this:

@Test
public void multipleItems() {
    Index<String, String> index = new Index<String, String>();
    index.add("key1", "value1");
    index.add("key2", "value2");
    index.add("key1", "value3");
    index.add("key2", "value4");
    index.add("key1", "value5");

    List<String> values = index.get("key2");

    assertEquals(2, values.size());
    assertEquals("value2", values.get(0));
    assertEquals("value4", values.get(1));
}

I am not aware of any implementation in the JVM. I could implement this myself, but I am hoping to find an existing implementation.

Recommendations?

SOLUTION

Based on the recommendations below, I ended up using the guava (and wrapping it as I didn't want to expose this to the rest of my app in case I found a better solution.

I used these settings for including through my gradle scripts: 'com.google.guava:guava-collections:r03'

My "wrapper" class looks like this:

public class Indexes<K, V> {

    private HashMultimap<K, V> keyToValuesMap = HashMultimap.create();

    public void put(K key, V value) {
        this.keyToValuesMap.put(key, value);
    }

    public Set<V> get(K key) {
        return this.keyToValuesMap.get(key);
    }

}

Upvotes: 0

Views: 412

Answers (3)

TofuBeer
TofuBeer

Reputation: 61536

To go along with the other answers, you can roll your own via Map<String, List<String>> or Map<String, Set<String>> if you cannot use a 3rd party library as well.

Upvotes: 3

Sign
Sign

Reputation: 1959

Guava, the java library from Google, has several types of Multimaps, including ListMultimap and SetMultimap, with a variety of implementations. There's also a wiki article.

Upvotes: 10

Ved
Ved

Reputation: 8767

You can use multimap in java. See this for more information.

http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/MultiMap.html

Upvotes: 0

Related Questions