Java List.indexOf and List.lastIndexOf
Locate the first or last occurrence of an equal element. Both methods return -1 when there is no match.
A simple example
List.indexOf and List.lastIndexOf
- Start with A, B, A
- Do this Locate the first and last A
- Result First and third positions
Syntax
stops.indexOf(stop)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind both visits to the market
A circular bus route visits the market on both the outward and return journeys. A timetable editor needs the first and last positions of the market to label the two visits correctly.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var stops = List.of("Depot", "Market", "Park", "Market");
System.out.println(stops.indexOf("Market") + " and " + stops.lastIndexOf("Market"));
}
}
1 and 3
The two Market entries occupy positions one and three in this zero-based route.
Check whether the route reaches the museum
A museum asks to appear on the printed timetable. Before adding another entry, the editor searches the current stop list and handles the missing result explicitly.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var stops = List.of("Depot", "Park");
System.out.println(stops.indexOf("Museum") == -1 ? "Add a new stop" : "Already listed");
}
}
Add a new stop
No element equals Museum, so indexOf returns -1.
Locate a transfer stop
A bus calls at Hill twice on its circular route. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.
What to watch for
Treat -1 as a distinct missing result before using it as an index.