@NotNull private static String generateRemoveIf( IteratorDeclaration declaration, CommentTracker ct, PsiExpression condition, String paramName) { return (declaration.getIterable() == null ? "" : ct.text(declaration.getIterable()) + ".") + "removeIf(" + paramName + "->" + ct.text(condition) + ");"; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if (!(element instanceof PsiLoopStatement)) return; PsiLoopStatement loop = (PsiLoopStatement) element; IteratorDeclaration declaration; declaration = IteratorDeclaration.fromLoop(loop); if (declaration == null) return; PsiStatement body = loop.getBody(); if (!(body instanceof PsiBlockStatement)) return; PsiStatement[] statements = ((PsiBlockStatement) body).getCodeBlock().getStatements(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); String replacement = null; CommentTracker ct = new CommentTracker(); if (statements.length == 2 && statements[1] instanceof PsiIfStatement) { PsiVariable variable = declaration.getNextElementVariable(statements[0]); if (variable == null) return; PsiExpression condition = ((PsiIfStatement) statements[1]).getCondition(); if (condition == null) return; replacement = generateRemoveIf(declaration, ct, condition, variable.getName()); } else if (statements.length == 1 && statements[0] instanceof PsiIfStatement) { PsiExpression condition = ((PsiIfStatement) statements[0]).getCondition(); if (condition == null) return; PsiElement ref = declaration.findOnlyIteratorRef(condition); if (ref != null) { PsiElement call = ref.getParent().getParent(); if (!declaration.isIteratorMethodCall(call, "next")) return; PsiType type = ((PsiExpression) call).getType(); JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); SuggestedNameInfo info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type); if (info.names.length == 0) { info = javaCodeStyleManager.suggestVariableName( VariableKind.PARAMETER, "value", null, type); } String paramName = javaCodeStyleManager.suggestUniqueVariableName(info, condition, true).names[0]; ct.replace(call, factory.createIdentifier(paramName)); replacement = generateRemoveIf(declaration, ct, condition, paramName); } } if (replacement == null) return; ct.delete(declaration.getIterator()); PsiElement result = ct.replaceAndRestoreComments(loop, replacement); LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result); CodeStyleManager.getInstance(project).reformat(result); }