2

I'd would like to use a collection of "key - value" pairs:

  • Which is the base for a JTable data model (TableModel implementation), so I need to access elements by their index/position (e.g. to implement Object getValueAt(int rowIndex, int columnIndex)). The collection must preserve the order of the elements. An ArrayList would be good for that.
  • Which allows to retrieve elements by the value of the key. A HashMap would be good for that.

The closest usable collection I've found is LinkedHashMap. It preserves the order and allows retrieval by key. However the access to an item is not possible by index/position, I must iterate over the items until the good one is found. This is not be time-effective.

Is there a better one than this one? Thanks.


(Question is similar to this one, but the solution provided uses the conversion toArray() which is not time-effective. If the set of pairs changes, the conversion needs to be done again.)

Community
  • 1
  • 1
mins
  • 6,478
  • 12
  • 56
  • 75

3 Answers3

1

There is no such collection implementation in the JRE.

But you can easily overcome this issue by using a Map<K,V> for storing the key-value pairs and an additional List<K> to store the keys in sequential order. You can then access a value either by key or by index using: keyValueMap.get(keys.get(index)).

You must make sure that modifications are always synchronized on both collections:

  • Add/Change an entry: if (keyValueMap.put(key, value) == null) keys.add(key)
  • Remove an entry: if (keyValueMap.remove(key) != null) keys.remove(key)

Note that this implementation assumes that values are never null. In case null values are required too, the code gets slightly more complex as we have to check for existence of an entry using keyValueMap.contains(key).

isnot2bad
  • 24,105
  • 2
  • 29
  • 50
  • Nice and easy. Thanks. Must be aware Map::put(k, v) also returns null when updating a previous entry where v was null, for implementations that allow null. – mins Sep 08 '14 at 17:41
  • @mins you're right, null values are not supported here. I've added a note to my answer to address this issue. – isnot2bad Sep 09 '14 at 08:49
0

Without implementing your own collection, it might be easiest to just have two collections, with the key-value reversed in the second one but otherwise ordered the same.

(wanted this to be a comment, but not enough rep yet)

Eben
  • 422
  • 2
  • 11
0

Apache Commons Collection has a ListOrderedMap class that makes what you want.

Pino
  • 7,468
  • 6
  • 50
  • 69
  • Appreciated, good to know. Thanks. May be the solution is using other classes from the package. For using only this one, I prefer to remain with the std API. – mins Sep 08 '14 at 17:45