Question

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. 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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top