Raji
Raji

Reputation:

Dictionary class

Is it possible to have multiple values, for a single key, in the Java dictionary class?

Upvotes: 3

Views: 1902

Answers (4)

Uri
Uri

Reputation: 89859

First, regarding the dictionary class: That class is considered obselete, the documentation recommends using Map instead.

This kind of collection you are seeking is called a multimap. You could implement one yourself with a list, but that is tedious.

You may want to use a MultiMap from either Apache Collections or from the Google Collections. While I am personally a fan of the apache collections, they do not really support generics, so a Google multimap may be safer.

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 362137

You can use a regular Map and have the values be Collections:

Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

map.put(0, Arrays.asList("foo", "bar"));
map.put(1, new ArrayList<String>());

map.get(1).add("blag");

Or you can use MultiMap from the Apache Commons Collections.

A MultiMap is a Map with slightly different semantics. Putting a value into the map will add the value to a Collection at that key. Getting a value will return a Collection, holding all the values put to that key.

For example:

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);

coll will be a collection containing "A", "B", "C".

(Unfortunately, MultiMap does not use generics.)

Upvotes: 2

JaredPar
JaredPar

Reputation: 755477

You should take a look at the MultiMap class from the apache commons collections

Upvotes: 2

Esteban Araya
Esteban Araya

Reputation: 29664

Sure. Use a list as the value.

Upvotes: 2

Related Questions