A list contains at least one value from another list (Java 8)

My function finds if one word is valid from the list of given words in the list on the page. Therefore, when the page contains words, I wrote it as follows: (Simplified version)

private boolean atLeastOneWordIsValidInThePage(Page page, Set<Long>  wordIdsToCheck) 
    Set<Long> wordIds = page.getWords().stream()
                .filter(word -> word.isValid())
                .map(word->getWordId())
                .collect(Collectors.toSet());
return words.stream().anyMatch((o) -> wordIds.contains(o));

Is this the best java 8 practice for writing it?
I want to stop the search when the first match is found.

+4
source share
1 answer

There is no need to open two separate streams. You should be able to bind anyMatchdirectly to the function mapas follows:

return page.getWords().stream()
            .filter(word -> word.isValid())
            .map(word->getWordId())
            .anyMatch((o) -> words.contains(o));
+3
source

Source: https://habr.com/ru/post/1668185/


All Articles