0

Have a class with attributes attr1, attr2, attr3 and attr4.

I am looking for a way to load a bunch of objects of that class in an array (or ArrayList or Map or whatever) and then being able to retrieve (search) these objects based on attr1 or attr2.

It looks like the way to go is HashMap but I will have to:

  1. if I want only one HashMap, I will have two entries for each object, one with key attr1 and one with key attr2

  2. have two HashMap objects, one with key attr1 and the other with key attr2 and based on what I am searching for, use the appropriate Map.

Is there any other elegant way of doing this? Is there a Map or Collection object that will allow me to provide multiple keys for an object?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
user2287359
  • 497
  • 1
  • 5
  • 16
  • Take a look at [this link](http://stackoverflow.com/questions/6768963/multiple-keys-to-single-value-map-java). Does this help you out? – fvrghl May 31 '13 at 22:01
  • Is it guaranteed that each object's attr1 is never the same as some other object's attr2? If no, you'd better use two maps. – Vlad May 31 '13 at 22:22

1 Answers1

1

I find the second solution with two Map objects quite elegant, each Map being a sort of index of your data. If you really want one single structure, then you can use Guava's Table, who is mapping values to a pair of keys.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58