Multiple Key Values ​​in a HashMap in Java

Can I save multiple values ​​corresponding to a key in a HashMap? If so, how?

+1
java hashmap
Sep 21 '12 at 19:04
source share
5 answers

Yes, this is called a chain. You will want to avoid the chain as much as possible, especially if the size of the chain starts to increase. A longer chain size will counteract the whole purpose of using a hash structure because the target should be as close to O (1) as possible.

Map<String, List<String>> hm = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("Value 1"); values.add("Value 2"); hm.put("Key1", values); 
+8
Sep 21 '12 at 19:13
source share

You can take a picture of the Guava library (former Google collections). It has Multimaps implementations that can store multiple values ​​for a single key.

For example, ListMultimap implementations allow you to duplicate key / value pairs that are stored in numerical order.

Here's how you use it:

 ListMultimap<String, Integer> numberClasses = ArrayListMultimap.create(); numberClasses.put("odd", 1); numberClasses.put("odd", 3); numberClasses.put("odd", 5); numberClasses.put("even", 2); numberClasses.put("even", 4); numberClasses.put("even", 6); assertEquals(Arrays.asList(1,3,5), numberClasses.get("odd")); assertEquals(Arrays.asList(2,4,6), numberClasses.get("even")); 

Another interesting example would be SetMultimap , which is very similar to ListMultimap, except that the values ​​for the key are stored in a set. (From a user’s point of view, I don’t know how exactly this is implemented.)

 SetMultimap<String, Integer> setMultimap= HashMultimap.create(); setMultimap.put("key1", 1); setMultimap.put("key1", 1); setMultimap.put("key1", 1); setMultimap.put("key1", 2); setMultimap.put("key2", 1); setMultimap.put("key2", 3); assertEquals(ImmutableSet.of(1,2), setMultimap.get("key1")); assertEquals(ImmutableSet.of(1,3), setMultimap.get("key2")); 
+10
Sep 21 '12 at 19:14
source share

Use Map<String, List<String>> .

+1
Sep 21 '12 at 19:06
source share

Strictly speaking, no.

But! You can have some Collection as your value and use it to store as many values ​​as possible.

0
Sep 21 '12 at 19:07
source share

Yes, but only if the value type stored in your Map is an array or List:

Map<String, List<String>> myMap

or

Map<String, String[]> myMap

But overall, bad practice is to create common data structures inside common data structures.

Why not write a domain-specific class that wraps the HashMap , and does it make it easier for you to check for a value, the number of elements per key, etc.?

0
Sep 21 '12 at 19:08
source share



All Articles