Collection<PsiImportStatementBase> (@NotNull final PsiJavaFile file) { final PsiImportList importList = file.getImportList(); if (importList == null) return null; final PsiImportStatementBase[] imports = importList.getAllImportStatements(); if (imports.length == 0) return null; Set<PsiImportStatementBase> allImports = ContainerUtil.newHashSet(imports); final Collection<PsiImportStatementBase> redundant; if (FileTypeUtils.isInServerPageFile(file)) { // remove only duplicate imports redundant = new ReferenceOpenHashSet<>(); ContainerUtil.addAll(redundant, imports); redundant.removeAll(allImports); for (PsiImportStatementBase importStatement : imports) { if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) { redundant.remove(importStatement); } } } else { redundant = allImports; final List<PsiFile> roots = file.getViewProvider().getAllFiles(); for (PsiElement root : roots) { root.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(@NotNull PsiJavaCodeReferenceElement reference) { if (!reference.isQualified()) { final JavaResolveResult resolveResult = reference.advancedResolve(false); if (!inTheSamePackage(file, resolveResult.getElement())) { final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase importStatementBase) { redundant.remove(importStatementBase); } } } super.visitReferenceElement(reference); } private static boolean inTheSamePackage(PsiJavaFile file, PsiElement element) { if (element instanceof PsiClass && ((PsiClass)element).getContainingClass() == null) { final PsiFile containingFile = element.getContainingFile(); return containingFile instanceof PsiClassOwner && Comparing.strEqual(file.getPackageName(), ((PsiClassOwner)containingFile).getPackageName()); } return false; } }); } } return redundant; }