Reputation: 7894
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.
Upvotes: 3
Views: 96
Reputation: 7853
You could also use apache commons BidiMap.
BidiMap exposes a method inverseBidiMap()
which gets a view of this map where the keys and values are reversed.
Hope that helps!
Upvotes: 0
Reputation: 14564
You could consider using the BiMap class from Google Guava (docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html), however I don't know that it would be more memory efficient.
private final Map<Integer, String> idToName = new BiMap<Integer, String>();
private final Map<String, Integer> nameToID = idToName.inverse();
And you will only have to add to the idToName
map:
idToName.put(name, id);
Upvotes: 0
Reputation: 198561
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.)
Upvotes: 5