StreamApiMigrationInspection: use Stream.of, etc. to iterate explicitly created array

This commit is contained in:
Tagir Valeev
2017-02-14 14:27:23 +07:00
parent 0f30ec30ef
commit 95ed6b3fd6
3 changed files with 74 additions and 1 deletions
@@ -932,7 +932,32 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
@Override
String createReplacement() {
return "java.util.Arrays.stream("+myExpression.getText() + ")";
if (myExpression instanceof PsiNewExpression) {
PsiArrayInitializerExpression initializer = ((PsiNewExpression)myExpression).getArrayInitializer();
if (initializer != null) {
PsiElement[] children = initializer.getChildren();
if (children.length > 2) {
String initializerText = StreamEx.of(children, 1, children.length - 1).map(PsiElement::getText).joining();
PsiType type = myExpression.getType();
if (type instanceof PsiArrayType) {
PsiType componentType = ((PsiArrayType)type).getComponentType();
if (componentType.equals(PsiType.INT)) {
return CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM + ".of(" + initializerText + ")";
}
else if (componentType.equals(PsiType.LONG)) {
return CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM + ".of(" + initializerText + ")";
}
else if (componentType.equals(PsiType.DOUBLE)) {
return CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM + ".of(" + initializerText + ")";
}
else if (componentType instanceof PsiClassType) {
return CommonClassNames.JAVA_UTIL_STREAM_STREAM + ".<" + componentType.getCanonicalText() + ">of(" + initializerText + ")";
}
}
}
}
}
return CommonClassNames.JAVA_UTIL_ARRAYS + ".stream(" + myExpression.getText() + ")";
}
@Nullable
@@ -0,0 +1,18 @@
// "Fix all 'Loop can be collapsed with Stream API' problems in file" "true"
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Test {
public String test(String other) {
return Stream.of("aaa", "bbb", "ccc", "ddd").filter(other::startsWith).findFirst().orElse(null);
}
public CharSequence test2(String other) {
return Stream.<CharSequence>of("aaa", "bbb", "ccc", "ddd").filter(s -> other.startsWith(s.toString())).findFirst().orElse(null);
}
public int test(int other) {
return IntStream.of(2, 4, 8, 16, 32, 64, 128, 256, 512, 1024).filter(i -> i > other).findFirst().orElse(-1);
}
}
@@ -0,0 +1,30 @@
// "Fix all 'Loop can be collapsed with Stream API' problems in file" "true"
public class Test {
public String test(String other) {
for(String s : new <caret>String[] {"aaa", "bbb", "ccc", "ddd"}) {
if(other.startsWith(s)) {
return s;
}
}
return null;
}
public CharSequence test2(String other) {
for(CharSequence s : new CharSequence[] {"aaa", "bbb", "ccc", "ddd"}) {
if(other.startsWith(s.toString())) {
return s;
}
}
return null;
}
public int test(int other) {
for(int i : new int[] {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}) {
if(i > other) {
return i;
}
}
return -1;
}
}