import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PrintInstances {
public void handlewords() throws IOException {
String path = "C:\\Users\\Documents\\NetBeansProjects\\src\\Wordlists.txt";
String path1 = "C:\\Users\\Documents\\NetBeansProjects\\src\\sample.txt";
------handle the wordlist
Features ft = new Features();
String content = ft.readFile(path);
String [] words = content.split(" ");
int a = words.length;----wordlist
-----handle the text file
StringBuffer bs = new StringBuffer();
FileReader fr = new FileReader(path1);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
bs.append(line+"\n");
}
br.close();
String str = bs.toString();
String [] word = str.split(" ");
int b = words.length;
// List<String> uniqueWords = new ArrayList<>();
List<String> list1 = new ArrayList<String>(words.length);
List<String> list2 = new ArrayList<String>(word.length);
/* for(int i=0;i<a;i++){
boolean unique = true;
for(int j=0;j<b;j++){
if(words[i].equals(word[j])){
unique = false;
break;
}
}
if(unique){
uniqueWords.add(word[i]);
}
}
for(String s: uniqueWords) {
System.out.println(s);
}*/
for(String s: words){
list1.add(s);
}
System.out.println(list1);
for(String x: word){
list2.add(x);
}
System.out.println(list2);
for(String x : list1){
for(String y: list2){
if(y.contains(x))
System.out.println(y);
}
}
}
public static void main(String[] args) throws IOException{
PrintInstances pi = new PrintInstances();
pi.handlewords();
}
}
我尝试在文本文件和单词列表文件中打印相同的单词,但是将它们放入Arraylist后,如果我使用y.equals(x)
,则不会打印任何内容。但如果我使用 contains ,就会出现更多结果,比如学生激活、激活、
还有一个问题,如果单词也在单词列表中,我可以获取文本文件中单词的索引吗?
最佳答案
有一种更简单的方法可以做到这一点:
final Set<String> set = new HashSet<>(list1);
set.retainAll(list2);
您的集合仅包含两个列表中的单词。
注意:如果顺序很重要,请使用 LinkedHashSet
而不是 HashSet
关于java - 如何在java中打印一个Arraylist中的单词以及另一个Arraylist中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389216/