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
falseA 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:
trueA 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
-1A 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
falseCommon 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
falseFunctions used in this recipe
- Arrays.stream() — Creates a stream from an array — for sums, filters and transformations.
- Arrays.binarySearch() — Quickly finds a value in a sorted array by repeatedly halving it.
- List.contains() — Checks whether a list contains an element.
- Arrays.asList() — Returns a fixed-size list backed by an array.