Data Structures – Best Way to Store 2 Keys and 3 Values in Java

data structuresenumjava

Well, I am having two keys and 3 values for that. Say key1,key2,value1,value2,value3. In future may the values can be increased like value4, value5 so on.

I need to get the values(value1,value2,value3) either by key1 or key2. The key1 will be unique, and key2 is not.

Currently, I am using ENUM for this configuration as like below

public enum EnumClass
{
Object1(Key1,Key2,Value1,Value2,Value3);
}

There will be more than 100 objects. As of now, I am using this ENUM class with 2 maps Map<key1,ENUM> and Map<key2,ENUM>

Is there any other solution that is better than the current solution?

Best Answer

If key2 is not unique, you can't use a Map to store a key2 -> (value1,value2,value3) relationship, since a Map asserts a 1-1 key/value relationship.

I would not worry about performance initially, since you have 100's of objects (as opposed to millions), and I would prefer simplicity/readability to begin with. Hide your lookup behind an interface (so that you can change your implementation later if you wish/need), and perhaps simply store a table of key1/key2/values, and perform your lookup against that simply by iterating through and building a list of matches.

Your repository methods would look something like:

ResultType byKey1(Key k);
Collection<ResultType> byKey2(Key k);

If key1 and key2 are distinct, you could implement a faster lookup by doing something like:

Map<Key,List<ResultType>>

so a lookup by key1 would give you a list of one (value1/value2/value3), whereas a lookup by key2 would give you a list of 'n' (value1/value2/value3). That would require a more complex initial data setup however. Hence I would suggest an initial simple table implementation behind a facade. You can implement optimisations later as required.