We have code with two complementary Maps like this:
private final Map<Integer, String> idToName = new HashMap<Integer, String>();
private final Map<String, Integer> nameToID = new TreeMap<String, Integer>();
Whenever we put something in one, we also put in the other (with the key and value reversed) like this:
nameToID.put(name, id);
idToName.put(id, name);
We're running into a memory problem with this application. It seems like there is a lot of duplication here. Is there a way to make this more memory-efficient? Some single structure that we could use? I realize that this might be at the cost of time-efficiency, so I'm interested in what the trade-offs would be.
This is exactly what Guava's BiMap does, though there's only so much added memory efficiency you can get. The biggest advantage of BiMap isn't so much memory efficiency as "it takes care of ensuring values are unique, and you can't forget to update the inverse map."
BiMap<Integer, String> idToName = HashBiMap.create();
idToName.put(1, "foo");
idToName.inverse(); // returns a BiMap mapping "foo" to 1
idToName.inverse().put("bar", 2); // idToName now has an extra mapping 2 -> "bar"
(Disclosure: I contribute to Guava.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With