diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLambda.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLambda.java index be9332b9479..1cad68ba121 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLambda.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryLambda.java @@ -43,6 +43,7 @@ import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.BlockTree; +import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; @@ -101,15 +102,26 @@ public Description matchMethod(MethodTree tree, VisitorState state) { if (state.isAndroidCompatible()) { return NO_MATCH; } + boolean[] usedInEnhancedForLoop = {false}; new TreePathScanner() { @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { + if (Objects.equals(getSymbol(node), sym)) { - replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath())); + Tree parent = getCurrentPath().getParentPath().getLeaf(); + if (parent instanceof EnhancedForLoopTree + && ((EnhancedForLoopTree) parent).getExpression().equals(node)) { + usedInEnhancedForLoop[0] = true; + } else { + replaceUseWithMethodReference(fix, node, name, state.withPath(getCurrentPath())); + } } return super.visitMethodInvocation(node, null); } }.scan(state.getPath().getCompilationUnit(), null); + if (usedInEnhancedForLoop[0]) { + return NO_MATCH; + } lambdaToMethod(state, lambda, fix, name, type); return describeMatch(tree, fix.build()); } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.java index 69e16564851..f80bb0eb527 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.java @@ -388,4 +388,26 @@ public void e() { "}") .doTest(); } + + @Test + public void iterable() { + testHelper + .addInputLines( + "Test.java", + "import java.util.stream.IntStream;", + "import java.util.ArrayList;", + "import java.util.stream.IntStream;", + "class Example {", + " void someLoopyCode() {", + " for (int i : someIterable()) {", + " // Do something.", + " }", + " }", + " private Iterable someIterable() {", + " return () -> IntStream.range(0, 42).boxed().iterator();", + " }", + "}") + .expectUnchanged() + .doTest(); + } }