1
votes

Which data structure should i use to store and retrieve the following data? (key1,val1)(key1,val2)(key1,val3)(key2,val4)(key2,val5)(key2,val6)(key3,val7)(key3,val8)(key3,val9)

Please help me.

5
Are all values distinct? - aioobe
Yes. All the values are distinct - Santhosh

5 Answers

6
votes

Take a look at Google Guava's Multimap and its subtypes ListMultimap and SetMultimap.

From Multimap's javadoc: A collection similar to a Map, but which may associate multiple values with a single key.

2
votes

Map<Key, Collection<Value>> is the best approach

1
votes

I don't know if it would work for you, but you may consider reversing key/value if values are unique and use a standard Map<ValueType, KeyType>

1
votes

You can have a Map where values are collections like List/Set Depending on whether your pairs are distinct or not.

If you have distinct pairs you can go for something like Set interface:

   Map<key, Set<value>>

   Ex Map<key, HashSet<Value>>

If you do not have have distinct pairs((key1, val1), (key1, val1)) you can go for List interface:

Map<key, List<value>>    
Map<key, ArrayList <Value>>
0
votes

We can use MultiValueMap From Commons collections.

Reference : http://commons.apache.org/proper/commons-collections/

Sample :

    MultiValueMap map = new MultiValueMap();
    map.put("SAN", 4);
    map.put("SAN", 6);
    map.put("TOM", 7);