Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 556
Bick Avatar asked Jan 29 '17 12:01

Bick


People also ask

How do you check if a list contains another list in Java 8?

The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection. So basically it is used to check if a List contains a set of elements or not.

How do I filter a list based on another list in Java 8?

One of the utility method filter() helps to filter the stream elements that satisfy the provided criteria. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition.


1 Answers

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));
like image 193
Chetan Kinger Avatar answered Oct 13 '22 00:10

Chetan Kinger