IntelliJ
Code Organization
Import Management
Programming Tool
IDE Functionality

IntelliJ Organize Imports

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In IntelliJ IDEA, the "Optimize Imports" action removes unused imports, sorts remaining imports by package, and collapses wildcard-eligible groups. The keyboard shortcut is Ctrl+Alt+O on Windows/Linux and Cmd+Opt+O on macOS. You can run it on a single file, a directory, a module, or the entire project. This article covers the manual shortcut, auto-optimization on save, import layout customization, and team configuration for consistent import ordering.

The Optimize Imports Shortcut

The primary way to organize imports is the keyboard shortcut:

PlatformShortcut
Windows / LinuxCtrl + Alt + O
macOSCmd + Opt + O

You can also access it from the menu: Code > Optimize Imports.

When triggered on an open file, IntelliJ performs three operations in sequence:

  1. Removes imports that are not used anywhere in the file.
  2. Sorts remaining imports according to the configured import layout.
  3. Replaces individual class imports with wildcard imports (*) when the threshold is met.

Before Optimization

java
1import java.util.*;
2import java.io.IOException;
3import java.util.List;
4import java.io.File;
5import java.util.Map;
6import com.google.common.collect.ImmutableList;
7import org.slf4j.Logger;
8import java.util.ArrayList;

After Optimization

java
1import com.google.common.collect.ImmutableList;
2import org.slf4j.Logger;
3
4import java.io.File;
5import java.io.IOException;
6import java.util.ArrayList;
7import java.util.List;

The duplicate coverage from java.util.* is resolved, java.util.Map is removed if unused, and the remaining imports are sorted into groups separated by blank lines.

Auto-Optimize on Save

Running the shortcut manually before every commit is easy to forget. IntelliJ can optimize imports automatically whenever you save or reformat.

Actions on Save (IntelliJ 2021.2+)

Go to Settings > Tools > Actions on Save and check Optimize imports.

This runs the import optimizer every time you trigger a save action (Ctrl+S / Cmd+S). It also works when IntelliJ auto-saves files on focus change.

On-the-Fly Import Optimization

For a more aggressive approach, go to Settings > Editor > General > Auto Import and enable:

  • Optimize imports on the fly: continuously removes unused imports as you edit.
  • Add unambiguous imports on the fly: automatically adds import statements when you reference a class with a single candidate.
text
1Settings path:
2  Editor
3    > General
4      > Auto Import
5        [x] Optimize imports on the fly
6        [x] Add unambiguous imports on the fly

The "on the fly" option is useful during active development. For large files, some developers find it distracting because imports shift while they type. The "on save" approach is a good middle ground.

Scope-Based Optimization

You can optimize imports across multiple files at once:

  • Right-click a directory in the Project view and select Optimize Imports.
  • Right-click a module to optimize all files in that module.
  • Select the project root to optimize the entire project.

IntelliJ shows a preview dialog listing all proposed changes before applying them. This is useful for large cleanup operations, such as removing unused imports after a major refactor.

You can also run it from the command line using IntelliJ's formatter integration:

bash
# Format and optimize imports via command line
idea format --optimize-imports -r src/

Customizing Import Layout

The default import ordering follows Java conventions, but many teams have custom rules. Configure the layout at Settings > Editor > Code Style > Java > Imports.

Key Configuration Options

SettingDefaultPurpose
Class count to use import with *5Threshold before import java.util.* replaces individual imports
Names count to use static import with *3Same threshold for static imports
Import layoutSee belowOrder and grouping of import packages

Default Java Import Layout

text
1import java.*
2import javax.*
3<blank line>
4import all other imports
5<blank line>
6import static all other imports

Google Java Style Import Layout

Many teams follow the Google Java Style Guide, which uses a different ordering:

text
import static all other imports
<blank line>
import all other imports

Google style also sets the wildcard threshold to Integer.MAX_VALUE (effectively disabling wildcards). To configure this in IntelliJ:

  1. Go to Settings > Editor > Code Style > Java > Imports.
  2. Set "Class count to use import with *" to a high number like 999.
  3. Set "Names count to use static import with *" to 999.
  4. Rearrange the import layout to put static imports first.

Kotlin Import Layout

For Kotlin files, the configuration is at Settings > Editor > Code Style > Kotlin > Imports. Kotlin's default is to use * imports for certain standard library packages. Adjust according to your team conventions.

Sharing Import Settings Across a Team

Inconsistent import settings between team members cause unnecessary diff noise and merge conflicts. IntelliJ provides two mechanisms for sharing settings.

EditorConfig

Create or update an .editorconfig file in the project root:

ini
[*.java]
ij_java_class_count_to_use_import_on_demand = 999
ij_java_names_count_to_use_static_import_on_demand = 999

This file is committed to version control and IntelliJ reads it automatically.

Shared Code Style Scheme

Export your code style settings via Settings > Editor > Code Style > Scheme > Export and commit the resulting XML file. Other team members import it, or you can place it in the .idea/codeStyles/ directory.

The .idea/codeStyles/Project.xml file, when committed, ensures all team members using IntelliJ share the same import layout and wildcard thresholds.

Integration with Code Formatting

Optimize Imports can be combined with the Reformat Code action for a single-step cleanup:

ActionWindows/LinuxmacOS
Reformat CodeCtrl + Alt + LCmd + Opt + L
Optimize ImportsCtrl + Alt + OCmd + Opt + O
Reformat + Optimize (via dialog)Ctrl + Alt + L then check "Optimize imports"Cmd + Opt + L then check "Optimize imports"

When you run Reformat Code with the dialog option (use Ctrl+Shift+Alt+L / Cmd+Shift+Opt+L), you can check "Optimize imports" and "Rearrange entries" to do everything in one pass.

Pre-Commit Hook

IntelliJ's commit dialog also supports running Optimize Imports before commit. In the Commit tool window, check Optimize imports under the "Before Commit" section. This ensures no unused imports slip into version control.

Other Languages

The Optimize Imports action works across all languages supported by IntelliJ:

LanguageBehavior
JavaRemoves unused, sorts, applies wildcard rules
KotlinRemoves unused, sorts, applies package-level star imports
PythonRemoves unused imports, sorts (respects isort config if plugin installed)
JavaScript/TypeScriptRemoves unused imports, sorts (respects project ESLint rules)
GoHandled by goimports integration

For Python projects, installing the IntelliJ isort plugin gives you compatibility with the popular isort tool that many teams already use in their CI pipeline.

Common Pitfalls

Running Optimize Imports on generated code or files managed by a code generator can cause conflicts. The generator may use a specific import order that IntelliJ rearranges, and the next generation overwrites IntelliJ's changes. Exclude generated source directories from optimization.

Setting wildcard import thresholds too low (e.g., 3) hides which classes are actually used. This makes code harder to read during review and can mask unused dependencies. Many style guides recommend disabling wildcards entirely or setting a high threshold.

Not sharing import settings across the team leads to import-ordering churn in pull requests. Two developers with different import layouts will reorder each other's imports on every file they both touch. Commit an .editorconfig or shared code style scheme to eliminate this.

Enabling "Optimize imports on the fly" in a project with very large files can cause momentary editor lag. If you notice typing delays, switch to the "on save" approach instead.

Forgetting to enable Optimize Imports in the pre-commit hook means unused imports accumulate over time. Enable it once in the commit dialog and IntelliJ remembers the setting for future commits.

Summary

  • Use Ctrl+Alt+O (Windows/Linux) or Cmd+Opt+O (macOS) to optimize imports in the current file.
  • Enable Actions on Save > Optimize imports for automatic cleanup on every save.
  • Right-click a directory or module to optimize imports across multiple files at once.
  • Customize import layout and wildcard thresholds at Settings > Editor > Code Style > Java > Imports.
  • Share settings via .editorconfig or committed .idea/codeStyles/Project.xml to prevent import ordering churn across the team.
  • Enable Optimize Imports in the pre-commit hook to catch unused imports before they reach version control.

Course illustration
Course illustration

All Rights Reserved.