Java hashtable bucket as an ArrayList

705 views Asked by At

I want to create a HashMap where each Key could have multiple Values. For example, the key umbrella could have values of red, black, and green. I have heard that the buckets in a Hashtable could be LinkedLists, ArrayLists, etc. How could I implement a bucket as an ArrayList so that I would be able to add items that match the key to the end of the list?

I want to have a something like Map<Key, Value>. If the Key exists, the Value will be added to the list of current Values.

1

There are 1 answers

0
Rob On BEST ANSWER

You should use Map<K, List<V>> map = new HashMap<>();

Instead of map.put(k, v), you will do something like this:

List<V> vs = map.get(k);
if (vs == null) {
    vs = new ArrayList<>();
    vs.add(v);
    map.put(k, vs);
} else {
    vs.add(v);
}