Library contents

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

  1. Start with A, B, A
  2. Do this Locate the first and last A
  3. Result First and third positions
The first match occurs at the beginning and the second at the end.

Syntax

Java syntax
stops.indexOf(stop)
Run these examples in Java

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

java Main.java

Find 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.

From the programvar stops = List.of("Depot", "Market", "Park", "Market")
Result1 and 3
Main.java
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"));
    }
}
Output
1 and 3

The two Market entries occupy positions one and three in this zero-based route.

Advertisements

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.

From the programvar stops = List.of("Depot", "Park")
ResultAdd a new stop
Main.java
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");
    }
}
Output
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.

GivenLake · Hill · Mill · Hill
Worked result1

What to watch for

Treat -1 as a distinct missing result before using it as an index.

Documentation for List.indexOf and List.lastIndexOf