0

I have a function that is supposed to return a list. The function is supposed to suggest different words when it parses through a file and identifies misspelled words. I must return a List. However, when I do so, I end up getting the same word suggested over and over again. I realize storing the "suggested" words in a Set would fix this problem (that way I only store one instance of any given suggestion). The only issue with that is I cannot return that Set since the return type is a List (and again I cannot change this). Is there a way around this issue?

I will provide the function below.

public static List<String> getSuggestions(String word){
    List<String> letters = Arrays.asList("a", "b", "c", "d", "e", "f", "g",
                                       "h", "i", "j", "k", "l", "m", "n",
                                       "o", "p", "q", "r", "s", "t", "u",
                                       "v", "w", "x", "y", "z"); 
    Set<String> suggestions = new HashSet();
    StringBuilder builder = new StringBuilder(word); 
    for(int i = 0; i <= builder.length(); i++){
        for(String string: letters){
            StringBuilder suggestion = new StringBuilder(builder.toString());
            suggestion.insert(i, string); 
            if(dictionary.contains(suggestion.toString().toLowerCase())){
                suggestions.add(suggestion.toString());
            }
        }
    }
    for(int i = 0; i <= builder.length()-2; i++){
        for(String string: letters){
            StringBuilder suggestion = new StringBuilder(builder.toString());
            char one = suggestion.charAt(i + 1);
            char two = suggestion.charAt(i);
            suggestion.replace(i, i + 1, String.valueOf(one));
            suggestion.replace(i+1, i + 2, String.valueOf(two));
            if(dictionary.contains(suggestion.toString().toLowerCase())){
                suggestions.add(suggestion.toString());
            }
        }
    }
    for(int i = 0; i <= builder.length(); i++){
        for(String string: letters){
            StringBuilder suggestion = new StringBuilder(builder.toString());
            suggestion.replace(i, i + 1, "");
            if(dictionary.contains(suggestion.toString().toLowerCase())){
                suggestions.add(suggestion.toString());
            }
        }
   }
   return suggestions;
}
A.Torres
  • 413
  • 1
  • 6
  • 16

1 Answers1

2

Assuming you want everything in-order change

Set<String> suggestions = new HashSet();

to

Set<String> suggestions = new LinkedHashSet<>();

And then change your final return from

return suggestions;

to

return new ArrayList<String>(suggestions);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249