Search code examples
javaarraysarraylisthashmapsubstring

How can I find words that start with a given string?


This is my browse method. I am trying to search through a hash map of "dictionaryEntry" objects, only looking at the "word" part of the entry. (b.word). The idea is that you could search the entire dictionary and return all words that start with the string given to the method. example you could return all the words that start with the string "sto". My idea was to iterate through the hash map, and if the substring of the word, starting at position zero and ending at the length of the input string, it will be added to an array list. Then the array list will be returned.

public ArrayList<dictionaryEntry> browse(String s) {
        ArrayList<dictionaryEntry> brow = new     ArrayList<dictionaryEntry>();
        for (dictionaryEntry b : hash.values()) {
            if ((b.word.substring(0, s.length())).equals(s)) {
                brow.add(new dictionaryEntry(b.word, b.definition));

        }

    }
    return brow;
}

Solution

  • An easier way to do this would be to use the Java String startsWith API. This function would then become the following:

    public ArrayList<dictionaryEntry> browse(String s) {
      ArrayList<dictionaryEntry> brow = new ArrayList<dictionaryEntry>();
      for (dictionaryEntry b : hash.values()) {
        if (b.word.startsWith(s)) {
          brow.add(new dictionaryEntry(b.word, b.definition));
    
        }
      }
      return brow;
    }