0

I want to check if the list "wordlist" has some elements from the list "list". If it has , these elements should be printed. Just have some difficulties with syntax to compare 2 lists in java. Here is my code:

File files = new File("E:/test/dictionary.txt");
String[] words = file.split(" ");
List<String> wordlist = Arrays.asList(words);
try {
    Scanner scanner = new Scanner(files);
    List<String> list = new ArrayList<>();

    while (scanner.hasNextLine()) {
        list.add(scanner.nextLine());
    }

    scanner.close();
    for (String word : wordlist) {
        System.out.println(word);
    }
    for (String oleg : list) {
        System.out.println(oleg);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Shar1er80
  • 9,001
  • 2
  • 20
  • 29
Oleg_08
  • 447
  • 1
  • 4
  • 23
  • possible duplicate of [Efficient intersection of two List in Java?](http://stackoverflow.com/questions/2400838/efficient-intersection-of-two-liststring-in-java) – Gil Jun 01 '15 at 00:08

2 Answers2

1

Perhaps I am misreading your question because the solution seems pretty simple to me. All you need to do is run a for-loop and use the ArrayList contains(Object O) method or run a nested for-loop and use the String equals(String O) method. See below.

METHOD 1:

for(int a = 0; a < wordlist.size(); a++)
    if(wordlist.contains(list.get(a)))
        System.out.println(list.get(a));

METHOD 2:

for(int a = 0; a < wordlist.size(); a++)
    for(int b = 0; b < wordlist.size(); b++)
        if(wordlist.get(a).equals(list.get(b));
            System.out.println(list.get(b));

In the second example I keep wordlist.size() as the factor in both loops because both list and wordlist should be the same size, or at least I assume that.

Also, with references or variables that more than one word, Java convention dictates that good practice would be to capitalize the first letter of all subsequent words, that is, wordlist should be wordList.

Hope this helps.

Ungeheuer
  • 1,393
  • 3
  • 17
  • 32
0

If I understand your question, use Collection.retainAll(Collection) (per the linked Javadoc to retain only the elements in this collection that are contained in the specified collection) like

wordlist.retainAll(list);
System.out.println(wordlist);
// for (String word : wordlist) {                              
//     System.out.println(word);                                
// }
// for (String oleg : list) {
//     System.out.println(oleg);
// }
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249