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
- Start with A, B, C
- Do this Remove the middle item
- Result A, C
Syntax
basket.remove(index)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaTake 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.
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));
}
}
Soap
Removing index one returns Soap and shifts Rice into the vacated position.
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.
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);
}
}
[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.
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());
}
}
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.