Library contents

Java List.remove by index or value

Remove an element by position or remove the first element equal to a given object. The two overloads have different return values.

A simple example

List.remove by index or value

  1. Start with A, B, C
  2. Do this Remove the middle item
  3. Result A, C
After removal the next item follows A directly.

Syntax

Java syntax
basket.remove(index)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Take a cancelled item off a packing list

A customer cancels the second item on an order after the packing list has printed. The picker uses its position to remove exactly that item and reads the removed label back to the customer.

ResultSoap
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var items = new ArrayList<>(List.of("Tea", "Soap", "Rice"));
        System.out.println(items.remove(1));
    }
}
Output
Soap

Removing index one returns Soap and shifts Rice into the vacated position.

Advertisements

Remove a ticket number that also looks like an index

A counter keeps ticket numbers in the order customers joined. The first ticket numbered one has been served, and another customer still holds a later ticket with the same number.

Result[8, 1]
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var tickets = new ArrayList<>(List.of(1, 8, 1));
        tickets.remove(Integer.valueOf(1));
        System.out.println(tickets);
    }
}
Output
[8, 1]

Supplying an Integer selects removal by value and removes only its first occurrence.

Clear the sign-in sheet for the next class

The morning class has finished and the office has already archived its attendance. The afternoon teacher reuses the working register and checks that it contains zero names before opening the door.

Result0
Main.java
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var register = new ArrayList<>(List.of("Mira", "Nia"));
        register.clear();
        System.out.println(register.size());
    }
}
Output
0

clear removes every element from the mutable list. The same register can now accept the next class.

What to watch for

On List<Integer>, remove(1) selects index one. Use remove(Integer.valueOf(1)) to remove the value one.

Documentation for List.remove by index or value