Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams: filter().count() vs anyMatch()

I want to find if a stream of strings has at least one occurrence of another String in a Set<String>. I came up with two solutions.

Performance wise, which approach is the best/recommended?

1)

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

2)

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

Here's streamFilter method:

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

filterKeywords: private Set<String> filterKeywords;

Or is there better approach than this?

like image 514
dazito Avatar asked Apr 09 '17 23:04

dazito


People also ask

What is the difference between the Anymatch () and findAny () stream methods?

The difference is in the type of the return value: Stream#findAny() : Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

Is Java stream filter faster than for loop?

The point to take home is that sequential streams are no faster than loops. If you use sequential streams then you don't do it for performance reasons; you do it because you like the functional programming style.

What is the difference between the findFirst () and findAny () method?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

How do you count streams in Java?

Stream count() method in Java with exampleslong count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation).


2 Answers

You should use anyMatch(this::streamFilter), look at the API on the anyMatch method below (emphasis mine) as it may not evaluate all elements of the stream where as count() obviously iterates the whole stream of elements.

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

The point is some of the stream methods like findFirst(), anyMatch(), findAny(), etc.. perform short-circuiting operations i.e., they may not evaluate all elements of the stream and you can refer here for more details.

like image 144
developer Avatar answered Sep 20 '22 13:09

developer


anyMatch doesn't always execute all the stream. It is the best approach.

like image 41
DJAM Silvère Gatien Avatar answered Sep 19 '22 13:09

DJAM Silvère Gatien