Search code examples
javadictionaryparameterizationmultikey

Parameterize MultiKeyMap with Multiple Keys


Is there any way to parameterize Apache Commons' MultiKeyMap with multiple keys? i.e.

MultiKeyMap<String, String, Integer, Float> m = new MultiKeyMap<String, String, Integer, Float>();

I originally had raw MultiKeyMaps but because of the frequency of these maps in my program I want to ensure consistency by parameterizing them.

I don't want to use MultiKeys because the data I am storing in the MultiKeyMap requires MultiKey<String, String, Integer>. However, MultiKey only supports keys of one type (MultiKey<String> or MultiKey<Integer>). If there is a workaround to this I am open to suggestions though.

To be clear, the overall problem I want to solve is this: I want to make sure the MultiKeyMaps in my program have the same types of keys by parameterizing them, but with different classes within the key (<K, K, K, V> = <String, String, Integer, Float>).

EDIT: It was suggested (in a now-deleted answer) I use a Triple<String, String, Integer>, and I tried:

private static MultiKeyMap<Triple<String, String, Integer>, Float> multiKeyMap = new MultiKeyMap<Triple<String, String, Integer>, Float>();
Triple<String, String, Integer> t = Triple.of("asdf", "asdf", 4);
multiKeyMap.put(t, 5);

However, at the third line of this statement it seems to expect something in the form of put(Triple<String, String, Integer> key1, Triple<String, String, Integer> key2, Float value). My question is now this: With this answer, do I now have no need for a MultiKeyMap? Should I be using a Map<Triple<String, String, Integer>, Float> now?

It is also worth noting that I need to iterate across this map frequently (with a large amount of data), which was easy when I had a non-parameterized MultiKeyMap because I could just change the parameters in the get() method as needed. Using a Triple, I believe I would have to create a new Triple instance each iteration; is this going to resource-heavy or is there a way around this?


Solution

  • You can use the Triple with any map impl (e.g. HashMap).

    You'll need to construct a Triple for each lookup, this will have a non-zero performance impact but shouldn't be a huge deal and will have the cleanest code imo.

    Suggest you run performance test before and after applying the Triple change and see if the impact is acceptable, and move forward with that if it is.