PsiElement () { PsiType loopVarExpressionType = myExtremumKeyExpr.getType(); if (loopVarExpressionType == null) return null; String method = getComparingMethod(loopVarExpressionType); if (method == null) return null; String inFilterOperation = myMax ? ">=" : "<="; PsiStatement loop = myTerminalBlock.getStreamSourceStatement(); PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(loop.getProject()); CommentTracker ct = new CommentTracker(); String extremumInitializer = ct.text(myExtremumKeyInitializer); PsiExpression condition = elementFactory.createExpressionFromText(ct.text(myExtremumKeyExpr) + inFilterOperation + extremumInitializer, loop); TerminalBlock blockWithFilter = myTerminalBlock.add(new StreamApiMigrationInspection.FilterOp(condition, myTerminalBlock.getVariable(), false)); String lambdaText = ct.lambdaText(myTerminalBlock.getVariable(), myExtremumKeyExpr); String comparator; if(myComparator == null) { comparator = CommonClassNames.JAVA_UTIL_COMPARATOR + "." + method + "(" + lambdaText + ")"; } else { String comparatorName = myComparator.getName(); if(comparatorName == null) return null; comparator = comparatorName; } String stream = blockWithFilter.generate(ct) + "." + getOperation(myMax) + "(" + comparator + ").orElse(null)"; return replaceWithFindExtremum(ct, myTerminalBlock.getStreamSourceStatement(), myExtremum, stream, myExtremumKey); }