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 19df9107db..90dc4f183f 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 @@ -17,6 +17,7 @@ import java.util.Queue; import java.util.Set; import java.util.SortedSet; +import java.util.function.Consumer; import java.util.function.IntFunction; import java.util.stream.Stream; import tech.picnic.errorprone.refaster.annotation.OnlineDocumentation; @@ -404,6 +405,19 @@ Optional after(Queue queue) { } } + /** Prefer {@link Collection#forEach(Consumer)} over more contrived alternatives. */ + static final class CollectionForEach { + @BeforeTemplate + void before(Collection collection, Consumer consumer) { + collection.stream().forEach(consumer); + } + + @AfterTemplate + void after(Collection collection, Consumer consumer) { + collection.forEach(consumer); + } + } + // XXX: collection.stream().noneMatch(e -> e.equals(other)) // ^ This is !collection.contains(other). Do we already rewrite variations on this? } 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 c5c3f686d5..68f6f79bfb 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 @@ -186,4 +186,8 @@ ImmutableSet> testRemoveOptionalFirstQueueElement() { ? Optional.ofNullable(new LinkedList().remove()) : Optional.empty()); } + + void testCollectionForEach() { + ImmutableSet.of(1).stream().forEach(String::valueOf); + } } 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 7d580729cc..0ebaa40f3b 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 @@ -136,4 +136,8 @@ ImmutableSet> testRemoveOptionalFirstQueueElement() { Optional.ofNullable(new LinkedList().poll()), Optional.ofNullable(new LinkedList().poll())); } + + void testCollectionForEach() { + ImmutableSet.of(1).forEach(String::valueOf); + } }