Multiple values for a key in HashMap in Java

32,273

Solution 1

Yes, this is called chaining. You will want to avoid chaining as much as possible, especially if the size of the chain starts increasing. Longer chain size will counter the whole purpose of using a hash structure because the goal is to come 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);

Solution 2

You could give a shot at Guava library (former Google collections). It has implementations of Multimaps which can store multiple values for a single key.

For example ListMultimap implementations allow duplicate key/value pairs which are kept in insertion order.

Here's how you'd 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 cool example would be SetMultimap, which is very similar to ListMultimap except that values for a key are kept in a set. (From user perspective, I don't know how exactly it 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"));

Solution 3

Use Map<String, List<String>>.

Share:
32,273
Anand
Author by

Anand

Java/J2EE developer

Updated on July 09, 2022

Comments

  • Anand
    Anand almost 2 years

    Is it possible to keep multiple values corresponding to a key in a HashMap? If yes, how?

  • Victor Sorokin
    Victor Sorokin almost 12 years
    or any other container, better suited for your task. For example, Set. Or just plain old array.
  • Neo
    Neo almost 10 years
    best answer i found for the problem :)
  • rajarajan2809
    rajarajan2809 almost 6 years
    how can i get the values of "List" for key "Key1"