Question

I have a ArrayList containing a lot of words, and a treeset cointaining the whole english dictionary. How do I compare the arraylist to the treeset to see if the words in the´arraylist is in the dictionary(treeset) adn print them out?

This is my code so far, but it doesnt work :

//variables
private TreeSet<String> dct = new TreeSet();
private String b;
static ArrayList<String> arr = new ArrayList<String>();

public static void permutation(String str) { 
    //find all permutaions from a Single string, store in arraylist.
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) 
        arr.add(prefix);

    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}


public void closeProgram(){
    //See if words from arraylist is in the dictionary
    ArrayList<String> arr = new ArrayList<String>();
    permutation(b);
    for(String str: arr)
        if(dct.contains(str)){
            System.out.println(str);
        }
}
Was it helpful?

Solution

Provided you don't care about duplicates in the list, the quickest way is to do this:

final Set<String> set = new LinkedHashSet<>(arr);
set.retainAll(dct);
for (final String str: set)
    System.out.println(str);

OTHER TIPS

You may try this:

Set<Object> dictionary = new TreeSet<>();
List<Object> words = new ArrayList<>();
words.retainAll(dictionary);
System.out.println("Words contained in the dictionary: " + words);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top