Use Stream::anyMatch instead of Stream::findFirst or Stream::findAny Info

When the matched data returned by Stream::findFirst or Stream::findAny is not used anywhere else, using Stream::anyMatch is more readable and convenient than using a chain of Stream::filter, Stream::findFirst or Stream::findAny and Optional::isPresent.

Detector ID
java/stream-anymatch-vs-findfirst@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1boolean streamCollectionNoncompliant(final Collection<String> col) {
2    // Noncompliant: uses a chain of "filter", "findFirst" and "isPresent" stream methods over anyMatch.
3    return col.stream()
4            .filter(Objects::isNull)
5            .findFirst()
6            .isPresent();
7}

Compliant example

1boolean streamCollectionCompliant(final Collection<String> col) {
2    // Compliant: uses anyMatch stream method over the others which is more readable and convenient.
3    return col.stream().anyMatch(Objects::isNull);
4}