Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a list contains an element

Short answer

contains() returns true if the element is in the list:

void main() {
    var fruits = List.of("apple", "banana", "cherry");
 
    IO.println(fruits.contains("banana"));
    IO.println(fruits.contains("mango"));
}

Output:

true
false

The position

indexOf() returns the index of the first occurrence, or -1:

void main() {
    var fruits = List.of("apple", "banana", "cherry");
    IO.println(fruits.indexOf("cherry"));
}

Output:

2

By a condition

To search by an object field, use anyMatch():

record User(String name, boolean admin) {}
 
void main() {
    var users = List.of(new User("Anna", false), new User("Oleg", true));
    IO.println(users.stream().anyMatch(User::admin));
}

Output:

true

Many checks

A list's contains() scans every element. If you check many times, put the elements into a HashSet — its lookup is almost instant:

void main() {
    var banned = new HashSet<>(List.of("spam@x.com", "bot@y.com"));
    var emails = List.of("anna@site.com", "bot@y.com");
 
    for (String email : emails) {
        IO.println(email + " " + (banned.contains(email) ? "blocked" : "ok"));
    }
}

Output:

anna@site.com ok
bot@y.com blocked

Common mistake

Searching for an object of your own class without equals(). A plain class compares references, so an object with the same content is not found. Records compare their fields automatically:

class PointClass {
    int x;
    PointClass(int x) { this.x = x; }
}
 
record PointRecord(int x) {}
 
void main() {
    IO.println(List.of(new PointClass(1)).contains(new PointClass(1)));
    IO.println(List.of(new PointRecord(1)).contains(new PointRecord(1)));
}

Output:

false
true

Functions used in this recipe

  • List.contains() — Checks whether a list contains an element.
  • List.indexOf() — Finds the position of an element in a list.
  • Stream.anyMatch() — Checks whether at least one element matches a condition.
  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.

Thanks for reading!

Donate to the site — we work hard for you.