Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java datastructure to map multiple keys to the same value

In Java I'm looking for a way to map multiple keys to the same value. Let's say I have the numbers 0-9 as keys, and "x", "y" and "z" as values as follows:

0->y
1->y
2->y
3->x
4->x
5->y
6->z
7->y
8->z
9->z

now x,y and z are really long strings, and I have millions of keys so I can't afford to store the strings multiple times. How would you go about it?

One idea I had was to create two arrays: an artificial second to key is generated to which the original keys are mapped and which in another array is the key to the actual values. That way the values are only stored once and the original keys can still be indirectly mapped to the values:

0->k1
1->k1
2->k1
3->k2
4->k2
5->k1
6->k3
7->k1
8->k3
9->k3

k1->y
k2->x
k3->z

Question though: Is there a better data structure for this?

like image 716
eikes Avatar asked Jun 15 '10 15:06

eikes


1 Answers

Any Map<Integer,String> will do - you are only storing a reference to the string, not a copy of it, so it doesn't matter how long it is.

If you are building the same string value multiple times, use intern() to get the same String object for the value each time.

like image 80
Pete Kirkham Avatar answered Sep 18 '22 17:09

Pete Kirkham