R – the best data structure for this in-memory lookup table

data-structuresdictionarylookup

I need to store a lookup table as an instance member in one of my classes. The table will be initialized when the object is constructed. Each "row" will have 3 "columns":

StringKey (e.g., "car")
EnumKey (e.g., LookupKeys.Car)
Value (e.g, "Ths is a car.")

I want to pick the data structure that will yield the best performance for doing lookups either by the StringKey or the EnumKey.

It's kind of awkward having 2 keys for the same dictionary value. I've never encountered this before, so I'm wondering what the norm is for this type of thing.

I could make a Key/Value/Value structure instead of Key/Key/Value, but I'm wondering what type of performance impact that would have.

Am I thinking about this all wrong?

Best Solution

You have two hashmaps.

  • One from StringKey to value.

  • One from EnumKey to value.

You do not have to duplicate all the Value instances, those objects can be shared between the two hashmaps.

If it's a LOT of items, you might want to use two treemaps instead of two hashmaps. But the essential principle ("Share the Values") applies to both structures. One set of Values with two maps.

Related Question