Introduce StreamMapFilter Refaster rule (#1467)

This commit is contained in:
Philipp Zeipert
2024-12-23 09:38:43 +01:00
committed by GitHub
parent d316e8ac70
commit 0fa59a5cec
3 changed files with 26 additions and 0 deletions

View File

@@ -297,6 +297,22 @@ final class StreamRules {
}
}
/**
* 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. */)

View File

@@ -141,6 +141,12 @@ final class StreamRulesTest implements RefasterRuleCollectionTestCase {
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()),

View File

@@ -141,6 +141,10 @@ final class StreamRulesTest implements RefasterRuleCollectionTestCase {
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)),