我有一个包含很多单词的ArrayList,以及一个包含整个英语词典的树集。如何比较arraylist和treeset以查看'arraylist中的单词是否在字典(treeset)中并打印出来?
到目前为止,这是我的代码,但它不起作用:
//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);
}
}
答案 0 :(得分:1)
如果您不关心列表中的重复项,最快的方法是:
final Set<String> set = new LinkedHashSet<>(arr);
set.retainAll(dct);
for (final String str: set)
System.out.println(str);
答案 1 :(得分:0)
你可以试试这个:
Set<Object> dictionary = new TreeSet<>();
List<Object> words = new ArrayList<>();
words.retainAll(dictionary);
System.out.println("Words contained in the dictionary: " + words);