Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.indexOf()

Finds the position of an element in a list.

Available since: Java 1.2

Syntax

int indexOf(Object o)
int lastIndexOf(Object o)

Parameters

ParameterTypeDescription
oObjectThe element to look for.

Return value

intThe index of the first (or last) occurrence, or `-1` if the element is absent.

Examples

The first and the last occurrence:

void main() {
    List<String> letters = List.of("a", "b", "c", "b");
    IO.println(letters.indexOf("b"));
    IO.println(letters.lastIndexOf("b"));
    IO.println(letters.indexOf("z"));
}

Output:

1
3
-1

Notes

A result of -1 means the element is absent — check it before using the index. Elements are compared with equals().

See also

Related recipes

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.