Reputation: 816
I want to create a HashMap
where each Key
could have multiple Value
s. For example, the key
umbrella could have value
s of red, black, and green. I have heard that the buckets in a Hashtable
could be LinkedList
s, ArrayList
s, 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 Value
s.
Upvotes: 0
Views: 717
Reputation: 6497
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);
}
Upvotes: 3