Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

2
  • 3
    There are many implementations like that e.g MultiValuedMap from apache commons or Multimap from Guava.Luckily you don't need to reinvent the wheel, although you can implement this solution on your own. Commented Nov 15, 2018 at 13:46
  • 3
    If you don't want to include a third party library, you can of course still use a Map<K,Collection<V>> to map keys to collections of values. When adding an entry, you check if the key is already associated with a collection; if it is, add the new value to the collection. If it's not create a new collection, add the value and put the collection into the map by the key. Using Java8 this all can be done simply via map.computeIfAbsent(key, (k,v) -> new ArrayList<V>()).add(value);. Commented Nov 15, 2018 at 14:06