7

My function finds if from a list of given words at list one word is valid in the page. So when page contains words I have written 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 it the best java 8 practice to write it?
I want to stop searching when the first match is found.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
Bick
  • 17,833
  • 52
  • 146
  • 251
  • 3
    I guess collecting stream into a set must have the same complexity as doing a set based lookup. So no need to construct `wordIds` in my opinion. – Pavel Horal Jan 29 '17 at 12:47
  • Some interesting approaches are in http://stackoverflow.com/questions/8708542/something-like-contains-any-for-java-set (just scroll through all the answers). – Pavel Horal Jan 30 '17 at 09:31

1 Answers1

6

There is no need to open two separate streams. You should be able to chain anyMatch directly to the map function as follows :

return page.getWords().stream()
            .filter(word -> word.isValid())
            .map(word->getWordId())
            .anyMatch((o) -> words.contains(o));
Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82