Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.contains()

Checks whether a list contains an element.

Available since: Java 1.2

Syntax

boolean contains(Object o)

Parameters

ParameterTypeDescription
oObjectThe element to look for.

Return value

boolean`true` if the element is in the list.

Examples

Looking for a string:

void main() {
    List<String> roles = List.of("admin", "editor");
    IO.println(roles.contains("admin"));
    IO.println(roles.contains("guest"));
}

Output:

true
false

Notes

Elements are compared with equals(), so your own classes must override it (records already do). The list is scanned in order — for frequent checks on large data a HashSet is faster.

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.