How to remove all unused imports from a Java file in VS code

Viewed 133

I use VS Code with the Extension Pack for Java.

When I have unused imports like

import java.util.ArrayList;
import java.util.stream.Collectors;

in my .java file I can remove each import individually via the "Quick Fix" action (Ctrl+.).

But how can I remove all unused imports from a Java file in VS Code?

2 Answers

You can use the shortcut key Shift+Alt+O . This will format your import code and of course remove unused imports.

For example, the original import code is like this

enter image description here

After using the Shift+Alt+O to format the import code

enter image description here

Fix them on just SAVING the file, the easiest way

Follow these steps to setup settings in VS Code.

  1. Press [Ctrl + , ] to open setting

  2. Click on that top-right icon (Open settings JSON) as shown in the below image marked in red. image

  3. Add this below code in settings.json file.

    "editor.codeActionsOnSave": { "source.organizeImports": true }

  4. Now just save it and its done

Related