Oleg_08
Oleg_08

Reputation: 487

check if there are any elements from one arraylist in another one and print the same elements

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();
}

Upvotes: 0

Views: 1322

Answers (2)

Ungeheuer
Ungeheuer

Reputation: 1443

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.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201437

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);
// }

Upvotes: 0

Related Questions