A list contains at least one value from another li

2019-04-09 17:38发布

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.

1条回答
男人必须洒脱
2楼-- · 2019-04-09 18:14

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));
查看更多
登录 后发表回答