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.
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 returntrue
for[email protected], Class Status - Freshman
- not just forFreshman
.Where does this leave you?
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).