[英]How to print out word in one Arraylist also in another Arraylist in java
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();
}
}
I have tried to printout the same word in text file and also in the wordlist file, but after I put those in Arraylist, if I use y.equals(x)
, nothings printed out. 我试图在文本文件和单词列表文件中打印相同的单词,但是在将它们放入Arraylist之后,如果我使用
y.equals(x)
,则什么也不会打印出来。 But if I used the contains to, more results came out, like student activate, activate, One more question, can I get the index of word in text file if the word is also in wordlist? 但是,如果我使用“包含”功能,则会出现更多结果,例如学生激活,激活,还有一个问题,如果单词也在单词列表中,我还能在文本文件中获得单词的索引吗?
There is a much more simple way to do that: 有一种更简单的方法可以做到这一点:
final Set<String> set = new HashSet<>(list1);
set.retainAll(list2);
Your set then only contains words which are in the two lists. 您的集合中仅包含两个列表中的单词。
Note: if order matters, use a LinkedHashSet
instead of a HashSet
注意:如果顺序很重要,请使用
LinkedHashSet
而不是HashSet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.