Search code examples
javaiteratortreesetstartswith

Java - How to efficiently show words from a words list as you type


I made a small Java program that loads a words list from a txt file which user chooses and stores it word-by-word in a TreeSet. Now I need to write a function that, whenever user types something into a text field (keyPressed), a function gets called and it finds/returns all words in this TreeSet that are beginning with letters that user typed in. I am new to using Sets so my solution would be to iterate from the first to the last element in the set and printing out the ones that satisfy the criteria:

Iterator <String>itr = dictionary.iterator();
String currentWord;
String tempUserInput = "av"; // Temporary, to simulate user input
while(itr.hasNext()){
   currentWord = itr.next();
   if (currentWord.startsWith(tempUserInput)) {
      System.out.println(currentWord); // Temporary, to simulate output
   }
}

This works properly but, since it needs to pass over 300000 words for a return value, my question is: Is there a more efficient solution to this problem?


Solution

  • Best stolution is to use a trie which is a suitable data structure for your problem. It is meant to be used to lower complexity while working of elements (usually strings) that share prefixes.

    Actually with some working I guess you could use a TreeSet by tricking the

    public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
    

    This could work by passing as fromElement the string which is currently typed and as the toElement the same string with added enough 'z' characters as the longest string in the set (this length could be calculated while populating the TreeSet). Eg:

    subSet("foo", true, "foozzzzzzzz", true);