void (@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { PsiConditionalExpression ternary = PsiTreeUtil.getNonStrictParentOfType(element, PsiConditionalExpression.class); TernaryNullCheck ternaryNullCheck = TernaryNullCheck.from(ternary); if (ternaryNullCheck == null) return; PsiVariable variable = ternaryNullCheck.myVariable; String name = variable.getName(); if (name == null) return; String inLambdaName = new VariableNameGenerator(ternary, VariableKind.PARAMETER).byName(name).byType(variable.getType()).generate(true); PsiExpression nullBranch = ternaryNullCheck.myNullBranch; PsiExpression notNullBranch = ternaryNullCheck.myNotNullBranch; PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); CommentTracker ct = new CommentTracker(); for (PsiReferenceExpression reference : VariableAccessUtils.getVariableReferences(variable, nullBranch)) { if (ExpressionUtil.isEffectivelyUnqualified(reference)) { PsiElement result = ct.replace(reference, "null"); if (nullBranch == reference) { nullBranch = (PsiExpression)result; } } } String origExpression = null; for (PsiReferenceExpression reference : VariableAccessUtils.getVariableReferences(variable, notNullBranch)) { PsiExpression qualifier = reference.getQualifierExpression(); if (qualifier != null) { if (!ExpressionUtil.isEffectivelyUnqualified(reference)) continue; if (origExpression == null) { origExpression = ct.text(reference); } ct.delete(qualifier); } ExpressionUtils.bindReferenceTo(reference, inLambdaName); } PsiLambdaExpression trueLambda = (PsiLambdaExpression)factory.createExpressionFromText("(" + variable.getType().getCanonicalText() + " " + inLambdaName + ")->" + ct.text(notNullBranch), ternary); PsiParameter lambdaParameter = Objects.requireNonNull(trueLambda.getParameterList().getParameter(0)); PsiExpression trueBody = Objects.requireNonNull((PsiExpression)trueLambda.getBody()); String ofNullableText = CommonClassNames.JAVA_UTIL_OPTIONAL + ".ofNullable(" + (origExpression == null ? name : origExpression) + ")"; String replacement = OptionalRefactoringUtil.generateOptionalUnwrap(ofNullableText, lambdaParameter, trueBody, ct.markUnchanged(nullBranch), ternary.getType(), !ExpressionUtils.isSafelyRecomputableExpression(nullBranch)); PsiElement result = ct.replaceAndRestoreComments(ternary, replacement); JavaCodeStyleManager.getInstance(project).shortenClassReferences(result); LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result); }