- #1
Arnoldjavs3
- 191
- 3
Homework Statement
Essentially, I am expected to have a method that can do a keyword search through my hashmap and return respective results. My hashmap is as follows:
HashMap<String, Person> phonebook
The string as a key is generally the name of the entry. A person object has 3 fields(Name, address, and phone number). In this case the person's name is also equal to the key. Essentially, when the user inputs a keyword it is expected to return results(in order) of all names and addresses that contain the keyword in alphabetical order.
(Hopefully I explained this properly)
Homework Equations
The Attempt at a Solution
So far I have this:
Java:
public void giveInfo(String keyword) {
ArrayList<Person> searcher = new ArrayList<Person>();
for (Map.Entry<String, Person> entry : phoneBook.entrySet()) {
if (entry.getKey().contains(keyword) || entry.getValue().getAddress().contains(keyword)) {
entry.getValue().retainAll(searcher);
}
Collections.sort(searcher);
}
for (Person results : searcher) {
System.out.println(results);
}
}
Things I know before hand:
I believe I need to implement the comparator and override my compareTo method so that it can effectively sort the arraylist.
I'm not sure exactly why retainAll isn't working but I believe I need to override hashcode and equals maybe? I think if the condition is true in the foreach loop then it should add the object from entry into the arraylist but I'm not sure.
Thanks.
If I need to show all of my source code let me know