diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/CollectionRules.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/CollectionRules.java index ba6146025ad..7a9802cb1fc 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/CollectionRules.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/CollectionRules.java @@ -74,6 +74,19 @@ int after(Collection collection) { } } + /** Prefer {@link Collection#contains(Object)} over more contrived alternatives. */ + static final class CollectionContains { + @BeforeTemplate + boolean before(Collection collection, S value) { + return collection.stream().anyMatch(value::equals); + } + + @AfterTemplate + boolean after(Collection collection, S value) { + return collection.contains(value); + } + } + /** * Don't call {@link Iterables#addAll(Collection, Iterable)} when the elements to be added are * already part of a {@link Collection}. diff --git a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestInput.java b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestInput.java index 369a84cba00..735587515c9 100644 --- a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestInput.java +++ b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestInput.java @@ -36,6 +36,10 @@ ImmutableSet testCollectionSize() { return ImmutableSet.of(Iterables.size(ImmutableSet.of(1)), ImmutableSet.of(2).asList().size()); } + boolean testCollectionContains() { + return ImmutableSet.of("foo").stream().anyMatch("bar"::equals); + } + boolean testCollectionAddAllToCollectionExpression() { return Iterables.addAll(new ArrayList<>(), ImmutableSet.of("foo")); } diff --git a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestOutput.java b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestOutput.java index 1f5380ec380..cf2040e33b0 100644 --- a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestOutput.java +++ b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/CollectionRulesTestOutput.java @@ -36,6 +36,10 @@ ImmutableSet testCollectionSize() { return ImmutableSet.of(ImmutableSet.of(1).size(), ImmutableSet.of(2).size()); } + boolean testCollectionContains() { + return ImmutableSet.of("foo").contains("bar"); + } + boolean testCollectionAddAllToCollectionExpression() { return new ArrayList<>().addAll(ImmutableSet.of("foo")); }