Skip to content

Commit

Permalink
Introduce CollectionForEach Refaster rule (#390)
Browse files Browse the repository at this point in the history
Fixes #387.
  • Loading branch information
amestoyg authored Dec 6, 2022
1 parent 1794d36 commit a6f794d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -404,6 +405,19 @@ Optional<T> after(Queue<T> queue) {
}
}

/** Prefer {@link Collection#forEach(Consumer)} over more contrived alternatives. */
static final class CollectionForEach<T> {
@BeforeTemplate
void before(Collection<T> collection, Consumer<? super T> consumer) {
collection.stream().forEach(consumer);
}

@AfterTemplate
void after(Collection<T> collection, Consumer<? super T> consumer) {
collection.forEach(consumer);
}
}

// XXX: collection.stream().noneMatch(e -> e.equals(other))
// ^ This is !collection.contains(other). Do we already rewrite variations on this?
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,8 @@ ImmutableSet<Optional<String>> testRemoveOptionalFirstQueueElement() {
? Optional.ofNullable(new LinkedList<String>().remove())
: Optional.empty());
}

void testCollectionForEach() {
ImmutableSet.of(1).stream().forEach(String::valueOf);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,8 @@ ImmutableSet<Optional<String>> testRemoveOptionalFirstQueueElement() {
Optional.ofNullable(new LinkedList<String>().poll()),
Optional.ofNullable(new LinkedList<String>().poll()));
}

void testCollectionForEach() {
ImmutableSet.of(1).forEach(String::valueOf);
}
}

0 comments on commit a6f794d

Please sign in to comment.