I am reading the contents of a txt file into a HashSet
. The file contains almost every word in the English language, and each word becomes a String in the HashSet
.
In my app, characters are being added to a String. I want to check whether this String is, or can become equal to, any of the Strings in the HashSet
. That is, say the HashSet
contains only the String apple. I have a String appl, and now I want to filter out the HashSet
until it becomes a set with only Strings that start with appl (in this case a set with only apple).
I can iterate over the entire HashSet
and use the startsWith(String)
method, as I build a new filtered HashSet
. But my initial HashSet
is very big, so my question is: Is there a more efficient way to do this (perhaps using a different type of Collection?)
Some code of how I would do it right now:
private HashSet<String> filter(String partOfWord){
HashSet<String> filteredSet = new HashSet<>();
for (String word : dictionary) { // dictionary is the full HashSet
if (word.startsWith(partOfWord)) {
filteredSet.add(word);
}
}
return filteredSet;
}