void (@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class); if (call == null) return; PsiExpression qualifier = call.getMethodExpression().getQualifierExpression(); if (qualifier == null) return; PsiType elementType = OptionalUtil.getOptionalElementType(qualifier.getType()); PsiMethodCallExpression nextCall = ExpressionUtils.getCallForQualifier(call); if (nextCall == null) return; String name = new VariableNameGenerator(qualifier, VariableKind.PARAMETER).byExpression(qualifier) .byType(elementType).byName("value").generate(true); CommentTracker ct = new CommentTracker(); PsiReferenceExpression methodExpression = nextCall.getMethodExpression(); ct.markRangeUnchanged(Objects.requireNonNull(methodExpression.getQualifierExpression()).getNextSibling(), methodExpression.getLastChild()); ct.markRangeUnchanged(methodExpression.getNextSibling(), nextCall.getLastChild()); PsiMethodCallExpression newNextCall = (PsiMethodCallExpression)nextCall.copy(); PsiExpression newQualifier = Objects.requireNonNull(newNextCall.getMethodExpression().getQualifierExpression()); newQualifier.replace(JavaPsiFacade.getElementFactory(project).createExpressionFromText(name, newNextCall)); String lambda = name + "->" + newNextCall.getText(); String replacement = ct.text(qualifier) + ".flatMap(" + lambda + ")"; PsiMethodCallExpression result = (PsiMethodCallExpression)ct.replaceAndRestoreComments(nextCall, replacement); LambdaCanBeMethodReferenceInspection.replaceLambdaWithMethodReference( (PsiLambdaExpression)result.getArgumentList().getExpressions()[0]); }