Skip to content

Commit

Permalink
Introduce StreamMapFilter Refaster rule (#1467)
Browse files Browse the repository at this point in the history
  • Loading branch information
zphilipp authored Dec 23, 2024
1 parent d316e8a commit 0fa59a5
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,22 @@ boolean after(Stream<T> stream) {
}
}

/**
* Prefer an unconditional {@link Map#get(Object)} call followed by a {@code null} check over a
* call to {@link Map#containsKey(Object)}, as the former avoids a second lookup operation.
*/
static final class StreamMapFilter<T, K, V> {
@BeforeTemplate
Stream<V> before(Stream<T> stream, Map<K, V> map) {
return stream.filter(map::containsKey).map(map::get);
}

@AfterTemplate
Stream<V> after(Stream<T> stream, Map<K, V> map) {
return stream.map(map::get).filter(Objects::nonNull);
}
}

static final class StreamMin<T> {
@BeforeTemplate
@SuppressWarnings("java:S4266" /* This violation will be rewritten. */)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ boolean testStreamFindAnyIsPresent() {
return Stream.of(1).findFirst().isPresent();
}

Stream<Integer> testStreamMapFilter() {
return Stream.of("foo")
.filter(ImmutableMap.of(1, 2)::containsKey)
.map(ImmutableMap.of(1, 2)::get);
}

ImmutableSet<Optional<String>> testStreamMin() {
return ImmutableSet.of(
Stream.of("foo").max(comparingInt(String::length).reversed()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ boolean testStreamFindAnyIsPresent() {
return Stream.of(1).findAny().isPresent();
}

Stream<Integer> testStreamMapFilter() {
return Stream.of("foo").map(ImmutableMap.of(1, 2)::get).filter(Objects::nonNull);
}

ImmutableSet<Optional<String>> testStreamMin() {
return ImmutableSet.of(
Stream.of("foo").min(comparingInt(String::length)),
Expand Down

0 comments on commit 0fa59a5

Please sign in to comment.