6

I need a collection that behaves something like C++ multimap, but I also need to be able to get elements by a range of keys.

Steinbitglis
  • 2,482
  • 2
  • 27
  • 40

3 Answers3

7

You can look into Google Collections. It has multiple implementations for MultiMap.

Matt Dearing
  • 9,286
  • 1
  • 23
  • 25
  • 2
    In particular. the Google Collections TreeMultimap class includes an asMap() method returning a SortedMap. You can then call methods like SortedMap.subMap() to retrieve mappings for a range of keys. – Jared Levy Apr 18 '10 at 07:18
4

There is no built-in multimap collection in Java. To solve this you can map to every key a list of values: Map<String, List<String>>, for example. Otherwise there are third-party libraries with implemented multimaps - here is one of them.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1

There is a simple hack around creating multimap sortable collections in java...Use the dataset TreeMap and for keys enter key*10^4+counter. This way you are storing duplicate key values in the map (by adding counter they are actually not duplicates, so you can store the in treeMap, but you know not to use the last four digits of the integer key values), however your dataset is being sorted using your original key values. Note that depending how large is your dataset you might want to adjust 10^n to make sure that it is larger then the number of entries in your data.