halloleo
halloleo

Reputation: 10464

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

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?

Upvotes: 7

Views: 8165

Answers (2)

Ahmed Hosny
Ahmed Hosny

Reputation: 480

Fix them on just SAVING the file, the easiest way

Follow these steps to automatically organize imports on file save in VS Code:

  1. Press Ctrl + F1 or Ctrl + SHIFT + P to open the command pallete

  2. Select Preferences: Open Workplace Settings (JSON)

  3. Add these lines to the bottom of the settings.json file.

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

Upvotes: 13

JialeDu
JialeDu

Reputation: 9883

UPDATA

Now that vs code Java has added a code action, you can use Remove all unused imports directly in quickfix to remove all unused imports.

enter image description here


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

Upvotes: 10

Related Questions