PsiLambdaExpression (@NotNull Project project, PsiLocalVariable variable) { if (variable == null) return null; PsiExpression initializer = variable.getInitializer(); if (initializer == null) return null; PsiLambdaExpression lambda = PsiTreeUtil.getParentOfType(variable, PsiLambdaExpression.class); if (lambda == null) return null; PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(lambda, PsiMethodCallExpression.class); if (call == null) return null; PsiExpression qualifier = call.getMethodExpression().getQualifierExpression(); if (qualifier == null) return null; String methodName = call.getMethodExpression().getReferenceName(); if (methodName == null) return null; PsiParameter parameter = ArrayUtil.getFirstElement(lambda.getParameterList().getParameters()); if (parameter == null) return null; ChainCallExtractor extractor = findExtractor(lambda, initializer, variable.getType()); if (extractor == null) return null; String newMethodName = extractor.fixCallName(call, variable.getType()); String mapOperation = extractor.buildChainCall(parameter, initializer, variable.getType()); PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); if (!mapOperation.isEmpty()) { qualifier = (PsiExpression)qualifier.replace(factory.createExpressionFromText(qualifier.getText() + mapOperation, qualifier)); } parameter = (PsiParameter)parameter.replace(factory.createParameter(variable.getName(), variable.getType(), parameter)); variable.delete(); LambdaRefactoringUtil.simplifyToExpressionLambda(lambda); PsiTypeElement typeElement = parameter.getTypeElement(); if (typeElement != null) { typeElement.delete(); } ExpressionUtils.bindCallTo(call, newMethodName); if (qualifier instanceof PsiMethodCallExpression) { PsiLambdaExpression newLambda = tryCast(ArrayUtil.getFirstElement(((PsiMethodCallExpression)qualifier).getArgumentList().getExpressions()), PsiLambdaExpression.class); if (newLambda != null) { LambdaCanBeMethodReferenceInspection.replaceLambdaWithMethodReference(newLambda); } } call = (PsiMethodCallExpression)CodeStyleManager.getInstance(project).reformat(call); return tryCast(ArrayUtil.getFirstElement(call.getArgumentList().getExpressions()), PsiLambdaExpression.class); }