Searching a TreeMap with concatenated values

37 views Asked by At

Suppose I add an item to a defined TreeMap like:

directory.put(personsLastName + personsFirstName, " Email - " + personsEmail 
                        + ", Class Status - " + studentStatus);

if I try to do something like:

boolean blnStudentExists = directory.containsValue("freshman");

it will always come out false. I am wondering if this has to do with the way I am populating the map? If so, how can I find all values in the map that are students? My goal is to print just students. Thanks.

1

There are 1 answers

1
ziesemer On BEST ANSWER

Please re-read the TreeMap Javadocs - or the generic Map interface, for that matter - and be very familiar with them for what you're trying to do here.

.containsValue() will search for specific, exact matches in the domain of values that you have inserted into your Map - nothing more, nothing less. You can't use this to search for partial strings. So if you inserted a value of [email protected], Class Status - Freshman, .containsValue will only return true for [email protected], Class Status - Freshman - not just for Freshman.

Where does this leave you?

  1. You could write your own "search" routine that iterates through each value in the map, and performs substring matching for what you are searching for. Not efficient for large numbers of values. You will also need to worry about the potential for confusing delimiters between fields, if/as you add more.
  2. You could create and use several parallel maps - one that maps to class statuses, another to emails, etc.
  3. You could use a database (or an embedded database - pick your flavor) - which looks to be what you're trying to create here anyway. Do you really need to re-create the wheel?

For this matter - you don't want to be searching by your values, anyway. This goes against the exact purpose of a Map - Hash, Tree, or otherwise. Searches by your keys are where any efficiencies will lie. In most implementations (including the out-of-box TreeMap and HashMap) - searches against values will have to scan the entire Map structure anyway (or at least, until it can bail out after finding the first match).