1

For instance, my treeMap is set as <String key, String value>

if(employeeList.containsKey(searchKey)){
    temp = "Employee: " + searchKey + ", Department: " + 
           departmentList.get(searchKey) + ", Salary: $" + employeeList.get(searchKey);
}

This loop obtains all the information associated to a specific key input by user. In my case, if I type the key (name of an employee) I would get his name, department, and salary.

Is there a way I can do the opposite? So, can I type the department (value) and get all the names of the employees (key) associated with that department?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
kakaday22
  • 157
  • 1
  • 8
  • 2
    I've added "java" tag as code seem to match Java coding style... Please confirm it is the language you are interested in. – Alexei Levenkov May 11 '14 at 04:59
  • The answer you're looking for is already here: http://stackoverflow.com/questions/1670038/does-java-have-a-hashmap-with-reverse-lookup – ethanfar May 11 '14 at 05:06
  • This is where using a database/ORM starts to become interesting; relational databases tend to be much better at this sort of “switching the query around” problem, since they encourage you to think about what you want to know and not how you get it. – Donal Fellows May 11 '14 at 06:10

1 Answers1

1

with current data-structure you must loop over the map:

ArrayList<String> relatedKeys = new ArrayList<String>();
for(String k : departmentList.keySet()){
  if(departmentList.get(k).equals(searchKey))
    relatedKeys.add(k);

at the end, you have a list of all related keys and can use

for(String k : relatedKeys)
  System.out.println(k);
Farvardin
  • 5,336
  • 5
  • 33
  • 54
  • This really is the only way to do this. Maybe you should also wrap this whole for loop in an if statement: if(departmentList.containsValue(searchKey)) { ... }. I'm thinking this should give a performance gain by only traversing the keySet when there actually is a corresponding key. – Kingand May 11 '14 at 05:51
  • never thought of doing this way, but the logic works. instead of adding it into an array I can add it to the string with no problem. – kakaday22 May 12 '14 at 01:24