Keyword search in a hashmap(using retainsAll) in java

  • Context: Comp Sci 
  • Thread starter Thread starter Arnoldjavs3
  • Start date Start date
  • Tags Tags
    Java Search
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
Arnoldjavs3
Messages
191
Reaction score
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
 
If it matters all I changed was instead of having the arraylist of person retainall the elements from entry.getValue() (I'm assuming this shouldn't work because it's just an object, not a list structure) i had simply added them into the arraylist if the condition was fulfilled.

Then I implemented comparator in the person object and everything compiled fine.