Troy Daniels
Troy Daniels

Reputation: 3598

Maintain java mapping from two different types of values in a single data structure

I have a collection of objects that look something like

class Widget {
  String name;
  int id;
  // Intuitive constructor omitted
}

Sometimes I want to look up an item by name, and sometime I want to look it up by id. I can obviously do this by

Map<String, Widget> mapByName;
Map<Integer, Widget> mapById;

However, that requires maintaining two maps, and at some point, I will (or another user who is unfamiliar with the double map) will make a change to the code and only update one of the maps.

The obvious solution is to make a class to manage the two maps. Does such a class already exist, probably in a third party package?

I am looking for something that lets me do something along the lines of

DoubleMap<String, Integer, Widget> map = new DoubleMap<>();
Widget w = new Widget(3, "foo");
map.put(w.id, w.name, w);
map.get1(3); // returns w
map.get2("foo"); // returns w

Upvotes: 2

Views: 171

Answers (1)

Thomas Bosch
Thomas Bosch

Reputation: 52

A simple solution could be, to write your own key class that includes both keys.

class WidgetKey {
  String id;
  String name;
  boolean equals() {...}
  boolean hashCode() {...}
}

Map<WidgetKey, Widget> yourMap;

Beware that you have to implement equals and hashCode in the WidgetKey class. Otherwise put/get and other map methods wouldn't work properly.

Upvotes: 1

Related Questions