PsiImportList (@NotNull PsiJavaFile file, @NotNull Predicate<? super Import> filter) { PsiImportList oldList = file.getImportList(); if (oldList == null) return null; // Java parser works in a way that comments may be included to the import list, e.g.: // import a; // /* comment */ // import b; // We want to preserve those comments then. List<PsiElement> nonImports = new NotNullList<>(); // Note: this array may contain "<packageOrClassName>.*" for unresolved imports! List<Import> imports = collectNamesToImport(file, nonImports) .stream() .filter(filter) .sorted(Comparator.comparing(o -> o.name)) .collect(Collectors.toList()); List<Import> resultList = sortItemsAccordingToSettings(imports, mySettings); Map<String, Boolean> classesOrPackagesToImportOnDemand = new HashMap<>(); collectOnDemandImports(resultList, mySettings, classesOrPackagesToImportOnDemand); MultiMap<String, String> conflictingMemberNames = new MultiMap<>(); for (Import anImport : resultList) { if (anImport.isStatic) { conflictingMemberNames.putValue(StringUtil.getShortName(anImport.name), StringUtil.getPackageName(anImport.name)); } } for (String methodName : conflictingMemberNames.keySet()) { Collection<String> collection = conflictingMemberNames.get(methodName); if (!classesOrPackagesToImportOnDemand.keySet().containsAll(collection)) { for (String name : collection) { classesOrPackagesToImportOnDemand.remove(name); } } } Set<String> classesToUseSingle = findSingleImports(file, resultList, classesOrPackagesToImportOnDemand.keySet()); Set<String> toReimport = calculateOnDemandImportConflicts(file, classesOrPackagesToImportOnDemand); classesToUseSingle.addAll(toReimport); try { boolean stringTemplates = HighlightingFeature.STRING_TEMPLATES.isAvailable(file); StringBuilder text = buildImportListText(resultList, classesOrPackagesToImportOnDemand.keySet(), classesToUseSingle, stringTemplates); for (PsiElement nonImport : nonImports) { text.append("\n").append(nonImport.getText()); } String ext = JavaFileType.INSTANCE.getDefaultExtension(); PsiFileFactory factory = PsiFileFactory.getInstance(file.getProject()); PsiJavaFile dummyFile = (PsiJavaFile)factory.createFileFromText("_Dummy_." + ext, JavaLanguage.INSTANCE, text, false, false); PsiUtil.FILE_LANGUAGE_LEVEL_KEY.set(dummyFile, file.getLanguageLevel()); PsiFileFactoryImpl.markGenerated(dummyFile); CodeStyle.reformatWithFileContext(dummyFile, file); PsiImportList newImportList = dummyFile.getImportList(); assert newImportList != null : dummyFile.getText(); if (oldList.isReplaceEquivalent(newImportList)) return null; return newImportList; } catch(IncorrectOperationException e) { LOG.error(e); return null; } }