How to delete all unused imports from current project in Intellij Idea
Asked Answered
D

2

47

I have been using Intellij Idea for quite some time now. I have a few questions though. Is there a way to delete all unused imports from all files in the current project?

I know that I can choose menu item Code > Optimize Imports (CTRL + ALT + O) to organize imports in individual files but since the application that I am working on has hundreds of files, this process does not make any sense. If there is no way of doing this, can I create a macro for this? If so, how do I do it?

Doctorate answered 14/8, 2018 at 4:4 Comment(2)
The question really is: Why wasn't that done as the files were created/edited? Unused imports should have shown as a warning, and anyone checking in code with warnings needs to be penalized, e.g. by forcing them to do this one file at a time.Degeneration
@Degeneration I do agree with you. But you see, for old applications, I guess the developers went sloppy with the approach. However, for all the new applications that we are developing, we make sure that the rules are set in Sonar CubeDoctorate
L
103

Click the project folder, then enter CTRL + ALT + O. It will handle all files under the folder:

enter image description here

Leprosarium answered 14/8, 2018 at 4:8 Comment(5)
I tried this and it worked (I guess). Does this process notify somewhere the number of imports that were deleted?Doctorate
@Doctorate I do not think it will. May be you can use the version control tool, such as Git, to see the differences.Leprosarium
Ah! Nice idea. Thanks.Doctorate
This changes every file in your project, though. Don't do this unless you want a massive commit even though nothing was really changed in the files (except for white space).Compulsion
For mac use CTRL + OPT + O.Independence
S
2

Easiest way is to enable Intellij -> Preferences -> Editor -> General -> Auto Import

Select Optimize imports on the fly; that will take care of removing unused imports on the fly

enter image description here

Sweetening answered 3/6 at 10:51 Comment(2)
Thanks @Sweetening for the suggestion. In my case the project already had a lot of files with unused imports. This is a great suggestion, though, and would help others. Wow! its been so long since i asked this question.Doctorate
Nice to know, its helpfulSweetening

© 2022 - 2024 — McMap. All rights reserved.