Are there any Datastructure like Map <K, V, W, ...>?

Sometimes I need to store more than one value for a key in Map . I know several methods to solve this problem, for example:

  • Creating your own implementation of Map<K,V,W>
    • hard to write, easy to reuse, problem if more values โ€‹โ€‹are needed
  • Use n Map<K,V>
    • easy to implement, takes up a lot of objects, the key is saved many times: what happens if you delete one key somewhere?
  • Use Map<K, Map<I, V>> and save the values โ€‹โ€‹with the second key
    • easy to implement, repetition issues may occur (null values), value keys must also be tracked
  • Create a class that stores K, V, W, ... , and use List<MyStorageClass> (or Map<K, MyStorageClass> )
    • seems like a good choice: easy to implement, but maybe you need to implement many interfaces (e.g. Compareable )
  • ... perhaps many more

but I wonder what is the best Java way (yes, I know: โ€œit dependsโ€)? Or is there even a language building function that I can use for minimal effort to implement it?

+4
source share
2 answers
  Sometimes i need to store more than one value to a key in a Map 

Why don't you use multimap? Multimap

+7
source

Check out MultiValueMap from Spring.

+2
source

All Articles