StreamToLoopInspection: fix when stream is inside multi-line expression lambda

This commit is contained in:
Tagir Valeev
2016-12-13 12:35:16 +07:00
parent 7b65a6919d
commit e4f40bf51f
3 changed files with 11 additions and 4 deletions

View File

@@ -297,8 +297,8 @@ public class StreamToLoopInspection extends BaseJavaBatchLocalInspectionTool {
int delta = nameElement.getTextOffset() - parent.getTextOffset();
PsiElement newParent;
if (parent instanceof PsiExpression) {
newParent = LambdaUtil
.extractSingleExpressionFromBody(((PsiLambdaExpression)RefactoringUtil.expandExpressionLambdaToCodeBlock(parent)).getBody());
newParent = LambdaUtil.extractSingleExpressionFromBody(
((PsiLambdaExpression)RefactoringUtil.expandExpressionLambdaToCodeBlock(parent, false)).getBody());
} else {
PsiElement blockStatement = parent.replace(factory.createStatementFromText("{" + parent.getText() + "}", parent));
newParent = ((PsiBlockStatement)blockStatement).getCodeBlock().getStatements()[0];

View File

@@ -986,6 +986,10 @@ public class RefactoringUtil {
}
public static PsiElement expandExpressionLambdaToCodeBlock(@NotNull PsiElement element) {
return expandExpressionLambdaToCodeBlock(element, true);
}
public static PsiElement expandExpressionLambdaToCodeBlock(@NotNull PsiElement element, boolean reformat) {
final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(element, PsiLambdaExpression.class);
LOG.assertTrue(lambdaExpression != null);
final PsiElement body = lambdaExpression.getBody();
@@ -997,7 +1001,8 @@ public class RefactoringUtil {
final String resultedLambdaText = lambdaExpression.getParameterList().getText() + "->" + blockText;
final PsiExpression expressionFromText =
JavaPsiFacade.getElementFactory(element.getProject()).createExpressionFromText(resultedLambdaText, lambdaExpression);
return CodeStyleManager.getInstance(element.getProject()).reformat(lambdaExpression.replace(expressionFromText));
PsiElement result = lambdaExpression.replace(expressionFromText);
return reformat ? CodeStyleManager.getInstance(element.getProject()).reformat(result) : result;
}
public interface ImplicitConstructorUsageVisitor {

View File

@@ -7,7 +7,9 @@ import java.util.stream.Stream;
public class Main {
public void test(String... list) {
DoubleSupplier s = () -> Stream.of(list).filter(Objects::nonNull).co<caret>llect(Collectors.averagingLong(String::length));
DoubleSupplier s = () -> Stream.of(list)
.filter(Objects::nonNull)
.co<caret>llect(Collectors.averagingLong(String::length));
System.out.println(s.getAsDouble());
}