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
.
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}
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}