Most efficient way to access 2D Maps (Maps of Maps) in Java? -
i'm implementing weightedslopeone prediciton algorithm recommender system , @ point in code need have 2 2d maps, 1 map<integer, map<integer, integer>>
, 1 map<integer, map<integer, double>>
as can understand accessing these , assigning values cumbersome procedure:
//the following 20 lines 1 line in python. sigh... hashmap<integer, integer> freqsforitem1 = frequencies.get(curitemid); //see if have value curitemid if (freqsforitem1 == null) { freqsforitem1 = new hashmap<integer, integer>(); freqsforitem1.put(curitemid_2, 1); frequencies.put(curitemid, freqsforitem1); } else {//see if have value curitemid+curitemid_2 integer freqforitem1item2 = freqsforitem1.get(curitemid_2); if (freqforitem1item2 == null) { //if don't have value item1+item2 put 1 freqsforitem1.put(curitemid_2, 1); } else {//we have value curitemid+curitemid_2 //so increment freqsforitem1.put(curitemid_2, freqforitem1item2 + 1); } }
so should using here instead of map<k1, map<k2, v>>
, or if there no better data structure available better way access , change values of such map?
instead of using map of maps, can create new, immutable class (with properly implemented equals()
, hashcode()
methods!) stores 2 integer keys, , use that key simpler map.
class mykey { int first; int second; // etc... } map<mykey, integer> freqs = new hashmap<mykey, integer();
this simplify accessing & assigning values, , moreso if decide need make key more complex.
Comments
Post a Comment