PsiElement () { PsiVariable variable = myTerminalBlock.getVariable(); String name = variable.getName(); if (name == null) return null; PsiType type = myExtremumInitializer.getType(); if (type == null) return null; Object initializerValue = ExpressionUtils.computeConstantExpression(myExtremumInitializer); if (initializerValue == null) return null; TerminalBlock blockWithMap = myTerminalBlock .add(new StreamApiMigrationInspection.MapOp(myLoopVarExpression, variable, myLoopVarExpression.getType())); final TerminalBlock terminalBlock; PsiType variableType = myLoopVarExpression.getType(); if(!Objects.equals(variableType, myExtremum.getType())) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(variable.getProject()); PsiExpression variableExpr = factory.createExpressionFromText(name, variable); terminalBlock = blockWithMap.add(new StreamApiMigrationInspection.MapOp(variableExpr, variable, type)); } else { terminalBlock = blockWithMap; } CommentTracker ct = new CommentTracker(); String inFilterOperation = myMax ? ">=" : "<="; PsiStatement loop = terminalBlock.getStreamSourceStatement(); PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(loop.getProject()); String extremumInitializer = ct.text(myExtremumInitializer); Object nonFilterableInitialValue = getNonFilterableInitialValue(type, myMax); final TerminalBlock filteredTerminalBlock; if (nonFilterableInitialValue != null && !nonFilterableInitialValue.equals(initializerValue)) { PsiExpression condition = elementFactory.createExpressionFromText(name + inFilterOperation + extremumInitializer, loop); filteredTerminalBlock = terminalBlock.add(new StreamApiMigrationInspection.FilterOp(condition, myTerminalBlock.getVariable(), false)); } else { filteredTerminalBlock = terminalBlock; } String stream = filteredTerminalBlock.generate(ct) + "." + getOperation(myMax) + "().orElse(" + extremumInitializer + ")"; return replaceWithFindExtremum(ct, loop, myExtremum, stream, null); }