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

一世执手 提交于 2019-12-09 18:33:58

问题


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:


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


来源:https://stackoverflow.com/questions/41920852/a-list-contains-at-least-one-value-from-another-list-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!