diff --git a/java/java-impl-inspections/src/com/intellij/codeInspection/streamMigration/CollectMigration.java b/java/java-impl-inspections/src/com/intellij/codeInspection/streamMigration/CollectMigration.java index 6eaa30922aa7..8e6a0041be89 100644 --- a/java/java-impl-inspections/src/com/intellij/codeInspection/streamMigration/CollectMigration.java +++ b/java/java-impl-inspections/src/com/intellij/codeInspection/streamMigration/CollectMigration.java @@ -850,8 +850,13 @@ class CollectMigration extends BaseStreamApiMigration { if (toArrayCandidate == null) return null; PsiReferenceExpression methodExpression = toArrayCandidate.getMethodExpression(); if (!"toArray".equals(methodExpression.getReferenceName())) return null; - if (!(PsiUtil.skipParenthesizedExprUp(toArrayCandidate.getParent()) instanceof PsiReturnStatement) && - usages.stream().anyMatch(usage -> !PsiTreeUtil.isAncestor(toArrayCandidate, usage, false))) { + /* We want to allow reusing the same empty collection in another branch of code after return. + * However, in this case, return should be on the same level as the stream itself. + * See beforeToArrayInBranch.java and beforeToArrayReusedCollection.java tests. + */ + if ((!(PsiUtil.skipParenthesizedExprUp(toArrayCandidate.getParent()) instanceof PsiReturnStatement stmt) + || stmt.getParent() != element.getParent()) && + ContainerUtil.exists(usages, usage -> !PsiTreeUtil.isAncestor(toArrayCandidate, usage, false))) { return null; } PsiLocalVariable var = tryCast(PsiUtil.skipParenthesizedExprUp(toArrayCandidate.getParent()), PsiLocalVariable.class); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/fuseStreamOperations/beforeToArrayInBranch.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/fuseStreamOperations/beforeToArrayInBranch.java new file mode 100644 index 000000000000..45c47eb540a6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/fuseStreamOperations/beforeToArrayInBranch.java @@ -0,0 +1,17 @@ +// "Fuse 'toArray' into the Stream API chain" "false" +import java.util.*; +import java.util.stream.*; + +class Test { + public Object[] getArray(String[] input, boolean f) { + List list = Arrays.stream(input) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + String[] data = new String[] {}; + if (f) { + return list.toArray(); + } + list.add("hello"); + return list.toArray(); + } +} \ No newline at end of file