Reputation: 2826
I'm implementing the WeightedSlopeOne prediciton algorithm for recommender system and at some point in the code I need to have 2 2D maps, one Map<Integer, Map<Integer, Integer>>
and one Map<Integer, Map<Integer, Double>>
As you can understand accessing these and assigning values is a cumbersome procedure:
//The following 20 lines are 1 line in Python. Sigh...
HashMap<Integer, Integer> freqsForItem1 = frequencies.get(curItemID);
//See if we have a value for curItemID
if (freqsForItem1 == null) {
freqsForItem1 = new HashMap<Integer, Integer>();
freqsForItem1.put(curItemID_2, 1);
frequencies.put(curItemID, freqsForItem1);
}
else {//See if we have a value for curItemID+curItemID_2
Integer freqForItem1Item2 = freqsForItem1.get(curItemID_2);
if (freqForItem1Item2 == null) {
//If we don't have a value for item1+item2 we just put 1
freqsForItem1.put(curItemID_2, 1);
}
else {//We already have a value for curItemID+curItemID_2
//So we just increment it
freqsForItem1.put(curItemID_2, freqForItem1Item2 + 1);
}
}
So what should I be using here instead of a Map<K1, Map<K2, V>>
, or if there is no better data structure available what is a better way to access and change the values of such a Map?
Upvotes: 0
Views: 110
Reputation: 700
so your key is an integer in both dimensions. why dont you use a
HashMap<Integer, Double> []
instead? or at least an
ArrayList<HashMap<Integer, Double>>
Would be much more performant
Upvotes: -1
Reputation: 359776
Instead of using a map of maps, you can create a new, immutable class (with properly implemented equals()
and hashCode()
methods!) that stores the two integer keys, and use that as the key for a simpler map.
class MyKey {
int first;
int second;
// etc...
}
Map<MyKey, Integer> freqs = new HashMap<MyKey, Integer();
This will greatly simplify accessing & assigning values, and even moreso if you decide you need to make your key more complex.
Upvotes: 2
Reputation: 4624
You can use Table
from Google's Guava
to do this without worrying of implementation.
Check Guava Page: https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table
Upvotes: 2