StringBuilder (@NotNull List<Import> imports, @NotNull Set<String> packagesOrClassesToImportOnDemand, @NotNull Set<String> namesToUseSingle, boolean stringTemplates) { Set<Import> importedPackagesOrClasses = new HashSet<>(); @NonNls StringBuilder buffer = new StringBuilder(); for (Import importedName : imports) { String name = importedName.name; boolean isStatic = importedName.isStatic; String packageOrClassName = getPackageOrClassName(name); boolean implicitlyImported = JAVA_LANG_PACKAGE.equals(packageOrClassName) || stringTemplates && STRING_TEMPLATE_STR.equals(name); boolean useOnDemand = implicitlyImported || packagesOrClassesToImportOnDemand.contains(packageOrClassName); Import current = new Import(packageOrClassName, isStatic); if (namesToUseSingle.remove(name)) { if (useOnDemand && importedPackagesOrClasses.contains(current)) { buffer.insert(buffer.lastIndexOf("import"), "import " + (isStatic ? "static " : "") + name + ";\n"); continue; } useOnDemand = false; } if (useOnDemand && (importedPackagesOrClasses.contains(current) || implicitlyImported)) continue; buffer.append("import "); if (isStatic) buffer.append("static "); if (useOnDemand) { importedPackagesOrClasses.add(current); buffer.append(packageOrClassName); buffer.append(".*"); } else { buffer.append(name); } buffer.append(";\n"); } for (String remainingSingle : namesToUseSingle) { buffer.append("import "); buffer.append(remainingSingle); buffer.append(";\n"); } return buffer; }