Search code examples
javahashtablehashsettreeset

Most Efficient Way to Check File for List of Words


I just had a homework assignment that wanted me to add all the Java keywords to a HashSet. Then read in a .java file, and count how many times any keyword appeared in the .java file.

The route I took was: Created an String[] array that contained all the keywords. Created a HashSet, and used Collections.addAll to add the array to the HashSet. Then as I iterated through the text file I would check it by HashSet.contains(currentWordFromFile);

Someone recommended using a HashTable to do this. Then I seen a similar example using a TreeSet. I was just curious.. what's the recommended way to do this?

(Complete code here: http://pastebin.com/GdDmCWj0 )


Solution

  • Try a Map<String, Integer> where the String is the word and the Integer is the number of times the word has been seen.

    One benefit of this is that you do not need to process the file twice.