I have a Java HashMap of type <MyType,Double>. The MyType class has two fields foo (of type String)and bar(of type Double). The equals and hashcode methods for MyType use only foo. Now given an object A of type MyType I need to get the matching entry from the Hashmap. What that means is
MyType A = new MyType();
A.foo = "foo";
A.bar = 0.0;
MyType B = new MyType();
B.foo = "foo";
B.bar = 1.0;
Map<MyType,Double> myMap = new HashMap<MyType,Double>();
myMap.put(B,5.0)
I need to extract the key B(and eventually its bar value) from myMap based on it’s equality with A (since their foo values are same) i.e. a function of the form
Double getBar(MyType type, Map<MyType,Double> map)
such that
getBar(A,myMap) returns 1.0
What is the best way to do that? I am not too sure of how this thing is designed in the first place but I am looking for an efficient way of doing this since myMap is expected to be really huge.
UPDATE: A slightly bigger context here is this. I have a set of MyType objects (say S). An external function works on it and creates a HashMap called myMap which calculates and associates a quantity of type Double with each object in the set. It also updates the bar field of each object in the set. What I get back is myMap. Now I need to update each element in my original set S such that each element’s bar value is replaced by what the bar value of the corresponding entry in the returned myMap is. So for each A in S I need to read the corresponding B in myMap, get its bar, and then set the bar of A to be same as bar of B.
If you do the
hashCodeandequalsbased on thefoo(which is what you indicate you are doing) then in your exampleAandBwould end up in the same bucket in the hashmap.As a result
getBar(A,myMap);would return5.0because that is what you put in the map-B.I mean you can search for
BusingAbut then eachputwould replace the previous one and I am not sure from your OP what your actual requirement isUpdate:
Update 2:
It seems that what you need is a way to access the keys in your
Mapdirectly. You could use do the following:Define:
and have
HashMap<MyType,Holder>instead. So in your method that does the calculation you update the map to add the result in theHolderobject where you also store thetype. I.e. instead ofmyMap.put(B,5.0);you do:myMap.put(B,new Holder(B,5.0));So you will have:
You have extra space requirement for storing the
typeas part of the value of the map as well but you will have gotten rid of the looping to actually find thetypeas it is now