Java threads: filter (). Count () vs anyMatch ()

I want to find if the stream of lines has at least one occurrence of another Stringin Set<String>. I came up with two solutions.

Efficiency, which approach is the best / recommended?

one)

return source.stream().filter(this::streamFilter).count() > 0;

2)

return source.stream().anyMatch(this::streamFilter);

Here's the streamFilter method:

private boolean streamFilter(String str) {
    return filterKeywords.contains(str.toLowerCase());
}

filterKeywords: private Set<String> filterKeywords;

Or is there a better approach than this?

+6
source share
2 answers

You should use anyMatch(this::streamFilter), look at the API using the method anyMatchbelow (my selection) as it may not evaluate all elements of the stream, where, as count()it obviously iterates over the entire stream of elements.

, . , . , false, .

- , findFirst(), anyMatch(), findAny() .. , .. .

+12

anyMatch . .

+1

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


All Articles