Java 25 (LTS) reference · List and ArrayList Methods

Java List indexOf() Method

Return the index of the first element equal to the given one, or -1. lastIndexOf() searches from the end.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

list.indexOf(object)

Parameters

ParameterDescription
object
Object
The value to find.

Return value

An index or -1.

Examples

Find positions
import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> steps = List.of("cart", "address", "payment", "address");
        System.out.println(steps.indexOf("address"));
        System.out.println(steps.lastIndexOf("address"));
        System.out.println(steps.indexOf("done"));
    }
}

Output

1
3
-1

Run this on your computer — see “Get Started” for setup.

Check for -1
import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> queue = List.of("ana", "ben", "cleo");
        int pos = queue.indexOf("cleo");
        System.out.println(pos >= 0 ? "position " + (pos + 1) : "not in queue");
    }
}

Output

position 3

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?