Skip to content

Commit 0680919

Browse files
authored
Support Lambda for Predicates.and() and Predicates.or() (#910)
This commit extends NoGuavaPredicatesAndOr recipe to handle Lambda as first parameter for Predicates.and() and Predicates.or() methods. Fixes #884
1 parent 51bcedb commit 0680919

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/main/java/org/openrewrite/java/migrate/guava/NoGuavaPredicatesAndOr.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ private J handlePredicatesMethod(J.MethodInvocation method, String operation) {
8383
return method;
8484
}
8585

86-
// If the first argument is a method reference, wrap it with a cast
87-
if (result instanceof J.MemberReference && result.getType() != null) {
86+
// If the first argument is a method reference or a lambda, wrap it with a cast
87+
if ((result instanceof J.MemberReference || result instanceof J.Lambda) && result.getType() != null) {
8888
String typeString = result.getType().toString().replace("com.google.common.base.", "");
8989
result = JavaTemplate.apply("((" + typeString + ") #{any()})", getCursor(), method.getCoordinates().replace(), result);
9090
}

src/test/java/org/openrewrite/java/migrate/guava/NoGuavaPredicatesAndOrTest.java

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -101,18 +101,38 @@ void replacePredicatesAndWithLambdas() {
101101
import com.google.common.base.Predicates;
102102
103103
class Test {
104-
Predicate<String> isNotNull = s -> s != null;
105-
Predicate<String> isLong = s -> s.length() > 5;
106-
Predicate<String> combined = Predicates.and(isNotNull, isLong);
104+
Predicate<String> combined = Predicates.and(s -> s != null, s -> s.length() > 5);
107105
}
108106
""",
109107
"""
110108
import com.google.common.base.Predicate;
111109
112110
class Test {
113-
Predicate<String> isNotNull = s -> s != null;
114-
Predicate<String> isLong = s -> s.length() > 5;
115-
Predicate<String> combined = isNotNull.and(isLong);
111+
Predicate<String> combined = ((Predicate<String>) s -> s != null).and(s -> s.length() > 5);
112+
}
113+
"""
114+
)
115+
);
116+
}
117+
118+
@Test
119+
void replacePredicatesOrWithLambdas() {
120+
//language=java
121+
rewriteRun(
122+
java(
123+
"""
124+
import com.google.common.base.Predicate;
125+
import com.google.common.base.Predicates;
126+
127+
class Test {
128+
Predicate<String> combined = Predicates.or(s -> s != null, s -> s.length() > 5);
129+
}
130+
""",
131+
"""
132+
import com.google.common.base.Predicate;
133+
134+
class Test {
135+
Predicate<String> combined = ((Predicate<String>) s -> s != null).or(s -> s.length() > 5);
116136
}
117137
"""
118138
)

0 commit comments

Comments
 (0)