Question

Which collection class should i use for the following data

(key1, value1)
(key1, value2)
(key2, value3)
(key3, value3)

keys and values are not distinct

No correct solution

OTHER TIPS

You can either roll your own implementation of a:

Map<Key, List<Value>> 

or use the Multimap from Guava, in their documentation they explain it as:

There are two ways to think of a Multimap conceptually: as a collection of mappings from single keys to single values:

a -> 1 a -> 2 a -> 4 b -> 3 c -> 5

or as a mapping from unique keys to collections of values:

a -> [1, 2, 4] b -> 3 c -> 5

The following blog post explains some of the advantages of using the Guava collection.

There is also the MultiValueMap from the Apache Commons Collections that solves the same problem should you have a preference when it comes to external libraries.

Another possibility for this use case is the MultiValueMap of Apache Commons Collections.

Map<List<String>,List<String>> map = new HashMap<List<String>,List<String>>();
List keys = new ArrayList();
keys.add("one");keys.add("one");keys.add("two");keys.add("three");
List values = new ArrayList();
values.add("First");values.add("First12");values.add("second");values.add("second");
map.put(keys, values);
System.out.println(map.keySet().toString());
System.out.println(map.values().toString());
System.out.println("map:"+map.toString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top