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
BiMapdoes, though there’s only so much added memory efficiency you can get. The biggest advantage ofBiMapisn’t so much memory efficiency as “it takes care of ensuring values are unique, and you can’t forget to update the inverse map.”(Disclosure: I contribute to Guava.)