StreamApiMigration: collect(joining()): allow separator addition based on counting loop variable value

This commit is contained in:
Tagir Valeev
2017-02-19 18:37:49 +07:00
parent 3cdd5e99ab
commit 21b3f46f1a
3 changed files with 40 additions and 4 deletions
@@ -15,6 +15,7 @@
*/
package com.intellij.codeInspection.streamMigration;
import com.intellij.codeInspection.streamMigration.StreamApiMigrationInspection.CountingLoopSource;
import com.intellij.codeInspection.util.LambdaGenerationUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
@@ -670,12 +671,22 @@ class CollectMigration extends BaseStreamApiMigration {
PsiExpression comparedToZero = getExpressionComparedToZero(condition);
if (comparedToZero == null) return null;
PsiMethodCallExpression maybeLength = tryCast(PsiUtil.skipParenthesizedExprDown(comparedToZero), PsiMethodCallExpression.class);
if (!isCallOf(maybeLength, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER, "length")) return null;
PsiLocalVariable builder = extractQualifierVariable(tb, maybeLength);
if (builder == null) return null;
PsiLocalVariable builder = null;
if (isCallOf(maybeLength, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER, "length")) {
builder = extractQualifierVariable(tb, maybeLength);
if (builder == null) return null;
}
else {
CountingLoopSource source = tb.getLastOperation(CountingLoopSource.class);
if (source == null ||
!ExpressionUtils.isZero(source.getExpression()) ||
!ExpressionUtils.isReferenceTo(comparedToZero, source.getVariable())) {
return null;
}
}
PsiMethodCallExpression call = tryCast(thenBranch.getExpression(), PsiMethodCallExpression.class);
if (!APPEND.test(call)) return null;
return extractQualifierVariable(tb, call) == builder ? call : null;
return builder == null || extractQualifierVariable(tb, call) == builder ? call : null;
}
static StringBuilderTerminal tryExtract(TerminalBlock tb, PsiMethodCallExpression call, PsiMethodCallExpression delimiterAppend) {
@@ -0,0 +1,11 @@
// "Replace with collect" "true"
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public void test(List<String> list) {
String sb = list.stream().limit(10).collect(Collectors.joining(","));
System.out.println(sb);
}
}
@@ -0,0 +1,14 @@
// "Replace with collect" "true"
import java.util.List;
public class Test {
public void test(List<String> list) {
StringBuilder sb = new StringBuilder();
for (int <caret>i=0; i<Math.min(10, list.size()); i++) {
if(i > 0) sb.append(",");
sb.append(list.get(i));
}
System.out.println(sb.toString());
}
}