1

If you had 1,000,000 keys (ints) that mapped to 10,000 values (ints). What would be the most efficient way (lookup performance and memory usage) to implement.

Assume the keys are not known ahead of time and are not continuous. Assume the values are random. i.e there is not a range of keys that map to a single value.

The easiest approach I can think of is a HashMap but wonder if you can do better by grouping the keys that match a single value.

Map<Integer,Integer> largeMap = Maps.newHashMap();
largeMap.put(1,4);
largeMap.put(2,232);
...
largeMap.put(1000000, 4);

Note: This is similar to my previous question (Mapping large set of Keys to a small set of Values) however the difference here is the keys are not continuous.

Chris
  • 1,299
  • 3
  • 18
  • 34
  • Just use a `HashMap`. 1M entries is no big deal, RAM is cheap. – fps Feb 04 '19 at 19:33
  • In addition to @FedericoPeraltaSchaffner's advice, you could have a second `HashMap` to map the original 10,000 values to the normalized values 0-9,999. The first `HashMap` now maps keys to normalized values. If the values are large (say 64-bit), and you map them to 0-9,999 (16-bit), you save 6 MB for 1,000,000 key-value pairs. You incur the time penalty for the second lookup and you spend some memory on the second hash map (although nowhere near 6 MB). – Cătălin Frâncu Feb 06 '19 at 10:12

0 Answers0