2

I want to implement Hash table with multiple values in java i.e

// if sample is a hashmap
sample.put(1,1);
sample.put(1,2);

and sample.get(1); will return 2 values.

How can i achieve this?

ericbn
  • 10,163
  • 3
  • 47
  • 55
starter
  • 75
  • 7

3 Answers3

6

You can use a Multimap instead. It keeps multiple values for a key in a list. There are implementations in commons-collections and in Guava.

Multimap<String, String> multimap = ArrayListMultimap.create();   
multimap.put("ducks", "Huey");
multimap.put("ducks", "Dewey");
multimap.put("ducks", "Louie");
Collection<String> ducks = multimap.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

It is similar to using a Hashmap where the values are lists, but you don't have to explicitly create the lists.

The same example done the do-it-yourself way looks like:

Map<String, List<String>> map = new HashMap<>();
map.put("ducks", new ArrayList<String>());
map.get("ducks").add("Huey");
map.get("ducks").add("Dewey");
map.get("ducks").add("Louie");
// or as an alternative to the prev 4 lines:
// map.put("ducks", new ArrayList<String>(
//     new String[] {"Huey", "Dewey", "Louie"}));
Collection<String> ducks = map.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

Note that you can use the Multimap as a builder and call asMap on it to return a map.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
2

Try HashMap<Key, List<Value>> You will need to manage the list, creating if it doesn't exist already, and adding to it if you need.

Guava also provides a Multimap implementation

JustinKSU
  • 4,875
  • 2
  • 29
  • 51
1

Do it this way

Map<String, List> map = new HashMap<String, List>();
List listOne = new ArrayList();
for(int i=0;i<4;i++){
    listOne.add(i);
}
List listTwo = new ArrayList();
for(int i=4;i<6;i++){
    listTwo.add(i);
}
map.put("listOne",listOne);
map.put("listTwo",listTwo);

Or you can even use Guava's Multimap

SparkOn
  • 8,806
  • 4
  • 29
  • 34