My text file contains datas like... dept->studentId-StudentData(name and email)..
IT-> 1->john->[email protected]
CSE->2->Santosh->[email protected]
IT->3->Mike->[email protected]
First,I have stored the studentId as key and studentData and dept as values in the hashmap and added in into arraylist(list of multiple objects-each list object for each row). Now, with dept as key, how do i retrieve StudentId and studentData from my list?
Say, With IT as my map key, how do I take data from my list and store it as value for the key? ( it should display both matching rows for IT).
I am new to working with collections and thanks in advance for any help given to complete this.
2 Answers
Why not use a Student Object instead of an ArrayList. It will also make your code more organized.
Make HashMap < String, Student > where string is the student id and Student is a class with all student attributes.
class Student{
String name;
String dept;
String email;
/** Getters & Setters **/
}
So next time you just go a map.get("STUDENT_ID_HERE").getName() or getDept() etc..
Your issue here is that the non-studentID data is stored as a value, rather than a key.
This is one of the difficulties when searching by non-key values. If your search value is not a key, then you need to iterate over all the values to find matches.
Keep your current solution, but implement a getDeptMapping(String deptID) method that iterates over all the values and retrieves the listings of matching department IDs. You can do this by map.EntrySet().
Some pseudocode:
public ArrayList<Entry<Key, Value> getDeptMappings(String deptID) {
//get entry mappings
Set<Entry<Key, Value>> entrySet = dataMap.entrySet()
//Create a Entry ArrayList to hold the results
ArrayList<Entry<Key, Value>> resultList = new ArrayList<Entry<Key. Value>>();
//Instanciate Set Iterator and retrieve first entry value
Iterator<Entry<Key, Value>> iter = entrySet.iterator();
Entry<Key, Value> currentEntry = iter.next();
while (iter.hasNext()) {
//Use currentEntry.getValue() to get the value list from currentEntry
//Compare list index points values where you stored the department ID during
//creation with the method parameter
//If comparison is true, add this entry to the resultList you
//created above.
}
//When iteration is complete, return the result list
}
Unlike regular map retrieval by key, which is O(1) or O(log n) depending on implementation, this solution executes in linear time and therefore is O(n). Note that you will have to insert your own type as Key and Value for the Entry object. I'm assuming that you used String as key and ArrayList<String> as value.