I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?
i can simply concatenate the two strings , but im sure there is a better way to do this.
I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?
i can simply concatenate the two strings , but im sure there is a better way to do this.
I see that many people use nested maps. That is, to map
Key1 -> Key2 -> Value
(I use the computer science/ aka haskell curring notation for(Key1 x Key2) -> Value
mapping which has two arguments and produces a value), you first supply the first key -- this returns you a (partial) mapKey2 -> Value
, which you unfold in the next step.For instance,
I am not sure that it is better or not than the plain composite key construction. You may comment on that.
You don't need to reinvent the wheel. Simply use the Guava's
HashBasedTable<R,C,V>
implementation ofTable<R,C,V>
interface, for your need. Here is an exampleHappy coding!
I have a similar case. All I do is concatenate the two strings separated by a tilde ( ~ ).
So when the client calls the service function to get the object from the map, it looks like this:
It is simple, but it works.
Why not create a (say)
Pair
object, which contains the two strings as members, and then use this as the key ?e.g.
Don't forget about equals() and hashCode(). See this blog entry for more on HashMaps and keys, including a background on the immutability requirements. If your key isn't immutable, then you can change its components and a subsequent lookup will fail to locate it (this is why immutable objects such as
String
are good candidates for a key)You're right that concatenation isn't ideal. For some circumstances it'll work, but it's often an unreliable and fragile solution (e.g. is AB/C a different key from A/BC ?).
This seems to be a terrible way to generate the hashCode: Creating a new string instance every time the hash code is computed is terrible! (Even generating the string instance once and caching the result is poor practice.)
There are a lot of suggestions here:
How do I calculate a good hash code for a list of strings?
For a pair of strings, that becomes:
That is a very basic implementation. Lots of advice through the link to suggest better tuned strategies.