PsiLambdaExpression (PsiLambdaExpression lambda) { PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(lambda, PsiMethodCallExpression.class); if (callExpression == null) return lambda; PsiExpression[] arguments = callExpression.getArgumentList().getExpressions(); if (!ContainerUtil.exists(arguments, SideEffectChecker::mayHaveSideEffects)) return lambda; CodeBlockSurrounder surrounder = CodeBlockSurrounder.forExpression(lambda); if (surrounder == null) return null; lambda = (PsiLambdaExpression)surrounder.surround().getExpression(); callExpression = PsiTreeUtil.getParentOfType(lambda, PsiMethodCallExpression.class); if (callExpression == null) return lambda; arguments = callExpression.getArgumentList().getExpressions(); PsiParameter[] parameters = lambda.getParameterList().getParameters(); if (arguments.length != parameters.length) return lambda; PsiStatement anchor = PsiTreeUtil.getParentOfType(lambda, PsiStatement.class, false); if (anchor == null) return lambda; List<PsiStatement> statements = new ArrayList<>(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(lambda.getProject()); for (int i = 0; i < arguments.length; i++) { PsiExpression argument = arguments[i]; PsiParameter parameter = parameters[i]; List<PsiExpression> sideEffects = SideEffectChecker.extractSideEffectExpressions(argument); if (!sideEffects.isEmpty()) { boolean used = VariableAccessUtils.variableIsUsed(parameter, lambda.getBody()); if (used) { String name = parameter.getName(); statements.add( factory.createStatementFromText(parameter.getType().getCanonicalText() + " " + name + "=" + argument.getText()+";", lambda)); argument.replace(factory.createExpressionFromText(name, parameter)); } else { Collections.addAll(statements, StatementExtractor.generateStatements(sideEffects, argument)); } } } BlockUtils.addBefore(anchor, statements.toArray(PsiStatement.EMPTY_ARRAY)); return lambda; }