What is ArrayUtils.contains in Java?
contains is a static method of the ArrayUtils class that checks whether the given array contains the given element or not.
Add apache commons-lang package
ArrayUtils is defined in the Apache Commons Lang package. The package can be added to the Maven project by adding the following dependency to the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
Importing ArrayUtils
You can import the ArrayUtils class as follows:
import org.apache.commons.lang3.ArrayUtils;
Syntax
public static boolean contains(final int[] array, final int valueToFind)
Parameters
final int[] array: array of elementsfinal int valueToFind: element to find in the array
Returns
This method returns true if the array contains the element, and returns false otherwise.
Code
Example 1
array = [1,2,3,4,5]elementToFind - 3
Applying the contains function will result in true, as the array contains the given element.
Example 2
array = [1,2,3,4,5]elementToFind - 100
Applying the contains function will result in false, as the array does not contain the given element.
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = new int[]{1,2,3,4,5,2,3,2,2,4};int elementToFind = 3;boolean check = ArrayUtils.contains(array, elementToFind);System.out.println("Array contains element " + elementToFind + " - " + check);elementToFind = 100;check = ArrayUtils.contains(array, elementToFind);System.out.println("Array contains element " + elementToFind + " - " + check);}}
Output
Array contains element 3 - true
Array contains element 100 - false