Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if an array contains a value

Short answer

Arrays have no contains() method. For an array of objects the easiest way is to wrap it in a list:

void main() {
    String[] colors = {"red", "green", "blue"};
 
    IO.println(Arrays.asList(colors).contains("green"));
    IO.println(Arrays.asList(colors).contains("black"));
}

Output:

true
false

A number array

For int[] use a stream:

void main() {
    int[] numbers = {4, 8, 15, 16};
    IO.println(Arrays.stream(numbers).anyMatch(n -> n == 15));
}

Output:

true

A plain loop

A loop is easy to understand and finds the element's position:

int indexOf(int[] array, int value) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return i;
        }
    }
    return -1;
}
 
void main() {
    int[] numbers = {4, 8, 15, 16};
    IO.println(indexOf(numbers, 15));
    IO.println(indexOf(numbers, 42));
}

Output:

2
-1

A sorted array

In a sorted array Arrays.binarySearch() finds an element very fast. A non-negative result is the index of the element:

void main() {
    int[] sorted = {2, 5, 9, 14, 20};
 
    IO.println(Arrays.binarySearch(sorted, 14));
    IO.println(Arrays.binarySearch(sorted, 7) >= 0);
}

Output:

3
false

Common mistake

Calling Arrays.asList() on an int[]. You get a list with one element — the array itself — and the search always returns false:

void main() {
    int[] numbers = {1, 2, 3};
 
    IO.println(Arrays.asList(numbers).size());
    IO.println(Arrays.asList(numbers).contains(2));
}

Output:

1
false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.