tryingHard
tryingHard

Reputation: 2084

How to sort imports in alphabeticall order in Intellij?

Is it possible to force IntelliJ to order imports alphabetically? So it should add import in lexicographical order and sort all imports that are not in good order when formatting the code.

Upvotes: 26

Views: 32873

Answers (4)

Ismandra Eka Nugraha
Ismandra Eka Nugraha

Reputation: 41

If your issue is the order between the java and javax imports, then you can simply move it by clicking the Up and Down button on the Layout static imports separately section.

move the import by clicking the up and down button

For example, if we have this order:

  • import java.*
  • import javax.*

Then if we do the Optimize Imports, it will order the imports like this:

import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

Upvotes: 0

Usama Sarwar
Usama Sarwar

Reputation: 9020

In case, none of the above answers work, try updating the ktlint version and then running ./gradlew ktlint. It was only solution for me that helped.

Upvotes: 0

Bas Leijdekkers
Bas Leijdekkers

Reputation: 26462

Reformatting code optimizes the imports by default, but it is also possible to invoke Code | Optimize Imports separately.

You can configure the order of imports in:
Preferences/Settings | Editor | Code Style | Java. Select the Imports tab and look under the Import Layout header at the bottom.

By default, imports are alphabetically ordered, except for the java.* and javax.* imports.

Upvotes: 24

bachman
bachman

Reputation: 181

I had the same problem. Building on what @bas-leijdekkers said that the default sort order is alphabetical, I was able to get my imports in the correct alphabetical order demanded by checkstyle, by doing this:

  • go into File > Settings
  • Go into Editor > Code Style > Java, Imports tab
  • Delete all entries in the "Import Layout" table. I had several in here by default, and maybe you do too. Note you cannot delete the "all other imports" entries, but you can reorder them depending upon your checkstyle requirements.
  • Click OK.
  • Then, use the Optimize Imports action in any offending file.

This worked for me, hope it helps you.

Upvotes: 5

Related Questions