2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

How would you implement them?
It sounds that the id and the name are unique. If this is the case just use Map<Object,Widget> and put each widget twice into that same map. You can have a class wrapping all this which exposes a single add(Widget) and two gets
For "equals" and "hashCode" there are several ways to implement. 1. Use your IDE to generate them 2. Use 3rd party libs like commons.apache.org/proper/commons-lang with EqualsBuilder and HashCodeBuilder 3. Do it by hand
I fail to see how this would work. I suppose you could implement hashCode as return 0 and equals as return this.id.equals(other) || this.name.equals(other), but that is unorthodox. When I am trying to get something out, I only have one of the two key values.
If you use HashMap as implementation of Map, implementing hashCode() return 0 is no good idea, as the hash value is used as primary key inside HashMap. Have you take a look at commons-lang library? Or if you don't want a new dependency have you tried to let it be generated by your IDE?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.