Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap with multiple Value [duplicate]

Tags:

java

multimap

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?

like image 244
starter Avatar asked May 14 '26 08:05

starter


2 Answers

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.

like image 54
Nathan Hughes Avatar answered May 16 '26 20:05

Nathan Hughes


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

like image 42
JustinKSU Avatar answered May 16 '26 20:05

JustinKSU