简体   繁体   中英

How can I print all the Keys from associated with a specific value?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM