void (Project project, PsiExpression iteratedValue, PsiReferenceExpression mapRef) { PsiMethodCallExpression forEachCall = ExpressionUtils.getCallForQualifier(iteratedValue); if (!ITERABLE_FOR_EACH.test(forEachCall)) return; PsiExpression[] args = forEachCall.getArgumentList().getExpressions(); PsiLambdaExpression lambda = tryCast(PsiUtil.skipParenthesizedExprDown(args[0]), PsiLambdaExpression.class); if (lambda == null) return; PsiParameterList parameterList = lambda.getParameterList(); if (parameterList.getParametersCount() != 1) return; PsiElement lambdaBody = lambda.getBody(); if (lambdaBody == null) return; PsiParameter keyParameter = Objects.requireNonNull(parameterList.getParameter(0)); mapRef = (PsiReferenceExpression)new CommentTracker().replaceAndRestoreComments(iteratedValue, mapRef); PsiType valueType = PsiUtil.substituteTypeParameter(mapRef.getType(), CommonClassNames.JAVA_UTIL_MAP, 1, true); List<PsiExpression> accesses = ParameterAccessCollector.collectParameterAccesses(keyParameter, mapRef, lambdaBody); String valueName = tryReuseValueVariable(lambdaBody, accesses, valueType); if (valueName == null) { valueName = new VariableNameGenerator(lambdaBody, VariableKind.PARAMETER).byType(valueType) .byName("k".equals(keyParameter.getName()) ? "v" : "value").generate(false); } for (PsiExpression access : accesses) { if (access instanceof PsiMethodCallExpression && access.isValid()) { new CommentTracker().replaceAndRestoreComments(access, valueName); } } String newLambdaText = "(" + keyParameter.getName() + "," + valueName + ")->" + lambdaBody.getText(); PsiExpression newLambda = JavaPsiFacade.getElementFactory(project).createExpressionFromText(newLambdaText, lambda); lambda.replace(newLambda); }