void (@NotNull PsiElement element) { final PsiForeachStatement statement = (PsiForeachStatement)element.getParent(); if (statement == null) { return; } final PsiExpression iteratedValue = statement.getIteratedValue(); if (iteratedValue == null) { return; } final PsiType iteratedValueType = iteratedValue.getType(); if (!(iteratedValueType instanceof PsiClassType)) { return; } CommentTracker tracker = new CommentTracker(); final String methodCall = tracker.text(iteratedValue, ParenthesesUtils.METHOD_CALL_PRECEDENCE) + ".iterator()"; final Project project = statement.getProject(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall, iteratedValue); final PsiType variableType = GenericsUtil.getVariableTypeByExpressionType(iteratorCall.getType()); if (variableType == null) { return; } @NonNls final StringBuilder newStatement = new StringBuilder(); newStatement.append("for(").append(variableType.getCanonicalText()).append(' '); final String iterator = new VariableNameGenerator(statement, VariableKind.LOCAL_VARIABLE) .byName("iterator", "iter", "it").generate(true); newStatement.append(iterator).append("=").append(iteratorCall.getText()).append(';'); newStatement.append(iterator).append(".hasNext();) {"); if (JavaCodeStyleSettings.getInstance(statement.getContainingFile()).GENERATE_FINAL_LOCALS) { newStatement.append("final "); } final PsiParameter iterationParameter = statement.getIterationParameter(); final PsiTypeElement parameterType = iterationParameter.getTypeElement(); final String typeText = parameterType == null ? iterationParameter.getType().getCanonicalText() : parameterType.getText(); newStatement.append(typeText).append(' ').append(iterationParameter.getName()).append(" = ").append(iterator).append(".next();"); final PsiStatement body = statement.getBody(); if (body == null) { return; } if (body instanceof PsiBlockStatement) { final PsiCodeBlock block = ((PsiBlockStatement)body).getCodeBlock(); final PsiElement[] children = block.getChildren(); for (int i = 1; i < children.length - 1; i++) { //skip the braces newStatement.append(tracker.text(children[i])); } } else { newStatement.append(tracker.text(body)); } newStatement.append('}'); PsiReplacementUtil.replaceStatementAndShortenClassNames(statement, newStatement.toString(), tracker); }