void (@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { if(!(element instanceof PsiMethodCallExpression terminalCall)) return; CodeBlockSurrounder surrounder = CodeBlockSurrounder.forExpression(terminalCall); if (surrounder == null) return; CodeBlockSurrounder.SurroundResult surroundResult = surrounder.surround(); terminalCall = (PsiMethodCallExpression)surroundResult.getExpression(); PsiType resultType = terminalCall.getType(); if (resultType == null) return; List<OperationRecord> operations = extractOperations(ChainVariable.STUB, terminalCall, true); if (operations == null) { operations = extractIterableForEach(terminalCall); } if (operations == null) { operations = extractMapForEach(terminalCall); } TerminalOperation terminal = getTerminal(operations); if (terminal == null) return; PsiStatement statement = surroundResult.getAnchor(); CommentTracker ct = new CommentTracker(); try { StreamToLoopReplacementContext context = new StreamToLoopReplacementContext(statement, operations, terminalCall, ct); registerVariables(operations, context); String replacement = ""; for (OperationRecord or : StreamEx.ofReversed(operations)) { replacement = or.myOperation.wrap(or.myInVar, or.myOutVar, replacement, context); } PsiElement previous = PsiTreeUtil.skipWhitespacesAndCommentsBackward(statement); PsiElement next = PsiTreeUtil.skipWhitespacesAndCommentsForward(statement); PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); for (PsiStatement addedStatement : ((PsiBlockStatement)factory.createStatementFromText("{" + replacement + "}", statement)) .getCodeBlock().getStatements()) { addStatement(statement, addedStatement); } PsiElement result = context.makeFinalReplacement(); if (result != null) { normalize(result); } if (previous != null) { PsiElement firstAdded = PsiTreeUtil.skipWhitespacesAndCommentsForward(previous); if (firstAdded != null) { ct.insertCommentsBefore(firstAdded); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); for (PsiElement e = firstAdded; e != null && e != next; e = e.getNextSibling()) { codeStyleManager.shortenClassReferences(e); } } } } catch (Exception ex) { LOG.error("Error converting Stream to loop", ex, new Attachment("Stream_code.txt", terminalCall.getText())); } }