String (String varName) { if (!PsiTypes.intType().equals(myType) && !PsiTypes.longType().equals(myType)) return null; Long start = null; Long step = null; Long last = null; for (PsiExpression element : myLoopElements) { if (!(element instanceof PsiLiteralExpression)) return null; Object value = ((PsiLiteralExpression)element).getValue(); if (!(value instanceof Integer) && !(value instanceof Long)) return null; long cur = ((Number)value).longValue(); if (start == null) { start = cur; } else if (step == null) { step = cur - start; if (step == 0) return null; } else if (cur - last != step || (step > 0 && cur < last) || (step < 0 && cur > last)) { return null; } last = cur; } if (start == null || step == null) return null; // Prefer for(int x : new int[] {12, 17}) over for(int x = 12; x <= 17; x+= 5) if (myLoopElements.size() == 2 && step != 1L && step != -1L) return null; PsiElement parent = myStatements.get(0).getParent(); boolean mustBeEffectivelyFinal = myExpressionsToReplace.stream() .map(ref -> PsiTreeUtil.getParentOfType(ref, PsiClass.class, PsiLambdaExpression.class)) .anyMatch(ctx -> ctx != null && PsiTreeUtil.isAncestor(parent, ctx, false)); if (mustBeEffectivelyFinal) return null; String suffix = PsiTypes.longType().equals(myType) ? "L" : ""; String initial = myType.getCanonicalText() + " " + varName + "=" + start + suffix; String condition = varName + (step == 1 && last != (PsiTypes.longType().equals(myType) ? Long.MAX_VALUE : Integer.MAX_VALUE) ? "<" + (last + 1) : step == -1 && last != (PsiTypes.longType().equals(myType) ? Long.MIN_VALUE : Integer.MIN_VALUE) ? ">" + (last - 1) : (step < 0 ? ">=" : "<=") + last) + suffix; String increment = varName + (step == 1 ? "++" : step == -1 ? "--" : step > 0 ? "+=" + step + suffix : "-=" + (-step) + suffix); return "for(" + initial + ";" + condition + ";" + increment + ")"; }