'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.



Solution 1:[1]

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 under Preferences | Editor | Code Style | Java under the Import Layout header. By default imports are alphabetically ordered, except for java.* and javax.* imports.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bas Leijdekkers
Solution 2 bachman