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
Syntax
list.indexOf(object)
Parameters
| Parameter | Description |
|---|---|
objectObject |
The value to find. |
Return value
An index or -1.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
list.contains()· Return true if the list holds an element equal to the given one (using equals()). O(n) for ArrayList.list.get()· Return the element at an index (0-based). Throws IndexOutOfBoundsException for an invalid index.- Java ArrayList · tutorial