1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Keyword search in a hashmap(using retainsAll) in java

  1. Dec 2, 2016 #1
    1. The problem statement, all variables and given/known data
    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)

    2. Relevant equations

    3. The attempt at a solution
    So far I have this:
    Code (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)) {
            for (Person results : searcher) {
    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 in to the arraylist but i'm not sure.


    If I need to show all of my source code let me know
  2. jcsd
  3. Dec 7, 2016 #2
    Thanks for the thread! This is an automated courtesy bump. Sorry you aren't generating responses at the moment. Do you have any further information, come to any new conclusions or is it possible to reword the post? The more details the better.
  4. Dec 7, 2016 #3
    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted