Explain Codes LogoExplain Codes Logo

How to remove unused imports in Intellij IDEA on commit?

java
best-practices
tools
code-management
Anton ShumikhinbyAnton Shumikhin·Dec 9, 2024
TLDR

To have IntelliJ IDEA get rid of unused imports during a commit:

  1. Open the Commit Dialog -> Gear Icon -> Check 'Optimize imports'
  2. Now, perform the commit. Unused imports? Pffft, they're history!
Commit -> Gear -> Optimize imports (✔)

Just by checking one option, your code becomes more concise and readable!

Set up your IDE like a pro

To make coding a smooth sail, customize your IDE with these tricks:

  • Choose Auto-Import: Go to Settings/Preferences -> Editor -> General -> Auto Import, then tick the Optimize imports on the fly checkbox. Your imports stay neat and tidy in real-time!
// The steps are almost as easy as pouring milk on cereal.
  • Arm yourself with the Save Actions Plugin: This allows you to optimize imports each time you save your file. Your code gets cleaner without you doing a thing!
// It's like having a personal cleaner for your code
  • Personalize Shortcuts: Regularly optimizing the imports by hand? Set a memorable shortcut and conquer!

Code management with Optimize Imports

Cleaner and more efficient code can be yours through batch optimization:

  • Cleaning the Whole House: To remove unused imports from your entire project or a module, select it in the Project view, then click: Code -> Optimize Imports.
// Wave your magic wand and Voilà! Rubbish be gone!
  • Routine Checks: A tidy project is a happy project. Make it a habit to run Optimize Imports before you make a big commit.
  • Code Style Settings: Define how imports are treated in Settings/Preferences -> Editor -> Code Style -> Java. Maybe you want to order your imports in a specific way? Or, you want a bit of space between each one? This is your playground.

Strategies to keep imports under control

Reduce import clutter further with these strategies:

  • Stay vigilant: Keep an eye on your code. When you see an unused import, zap it out of the code!
  • Collective responsibility: Encourage your programming pals to keep their imports optimized - team efforts produce cleaner code.
  • Code Reviews: Leave notes on missed optimization opportunities during team code reviews.

Additional tricks for import management

Below are some bonus tips to keep on top of your imports:

  • Shortcut Heaven: For Windows/Linux use <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>O</kbd>, for Mac <kbd>Cmd</kbd> + <kbd>Option</kbd> + <kbd>O</kbd> to manually call the Optimize Imports action. Sneaky, right?
  • Reformat Code: The Reformat code box in the commit dialog is like a code beautician! Activate it alongside the import optimization for a more uniformed code styling.
  • Control Imports Layout: In the code style settings, tweak your imports layout to define a uniform structure. Perhaps you want all Java imports together, separated from third-party libraries?