List.contains()
Checks whether a list contains an element.
Available since: Java 1.2
Syntax
boolean contains(Object o)Parameters
| Parameter | Type | Description |
|---|---|---|
| o | Object | The 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
falseNotes
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
- List.indexOf() — Finds the position of an element in a list.
- Set.contains() — Checks whether a set contains an element.
- Stream.anyMatch() — Checks whether at least one element matches a condition.
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.