Check if array contains value in java
This article will detail out 5 different methods to check if array contains a value in java with example programs.
Following are the methods to check the presence of a value in java array

We will be performing the following tasks :

  1. Check whether a string array contains a given string value.
  2. If the string exists in the array, then get the index of its position in array.

Method 1: Looping over the array

This is a conventional and most used method where the array of strings is iterated using a for loop and the value at every index is compared with the value to be searched in the array.
A boolean variable is set if any array value matches with the string.
At the end of the loop, this boolean variable is checked to determine if the array contains the string.

public class ArrayContainsChecker { 
  public static void main(String[] args) { 
    methodOne(); 
  } 

  static void methodOne() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // initialize boolean variable 
    boolean isExists = false; 
    // iterate over array 
    for (int i = 0; i < array.length; i++) { 
      // get the value at current array index 
      String arrayValue = array[i]; 
      // compare values 
      if (valueToSearch.equals(arrayValue)) { 
        isExists = true; 
        // if value is found, terminate the loop 
        break; 
      } 
    } 
    if (isExists) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Use == operator to check for equality when comparing primitive types such as int, long, float, double etc.
Note that in this example, we are using a simple for loop with an index.
But, we may also use an enhanced for loop to iterate over the array, if we do not require the index of the value to check.

Method 2: Using List.contains()

Another method to check if an array contains an element is by using a list.
This method first converts the array to a java.util.List and then uses contains() method of java.util.List to check if the string exists in the list.

contains() method returns true if the value supplied as argument exists in the list and false otherwise. In other words, it checks if the list contains the supplied value.
Array is converted to a list using asList() method of java.util.Arrays.
This method takes an array as argument and returns a List with its elements populated with the contents of array.

import java.util.Arrays; 
import java.util.List; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodTwo(); 
  } 

  static void methodTwo() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // convert the array to a list 
    List list = Arrays.asList(array); 
    // check if string exists in list 
    if (list.contains(valueToSearch)) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

 

String is found in the array

Method 3: Using Apache Commons Library

This method utilizes ArrayUtils class from Apache Commons Library.
This class has a method contains() which takes two arguments : an array and a value. It searches for the value in the array and returns true if the value is found in the array, false otherwise.

import org.apache.commons.lang.ArrayUtils; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodThree(); 
  } 

  static void methodThree() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // check if string exists in array 
    if (ArrayUtils.contains(array, valueToSearch)) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Apache Commons can be included using the following dependencies of Maven and Gradle. Use as per to the build tool suitable to you.

Maven

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

Gradle

compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

Method 4: Using Arrays.binarySearch()

java.util.Arrays has a binarySearch() method which searches for a value in an array using binary search algorithm.
This method takes two arguments :
1. an array, and
2. the item to search in the array
and returns the index of the item in the array.
It returns -1 if the element is not found in the array. Note that this method requires the array to be sorted before performing the search operation.

import java.util.Arrays; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodFour(); 
  } 

  static void methodFour() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "one"; 
    // sort the array 
    Arrays.sort(array); 
    // search the value and get its index 
    int index = Arrays.binarySearch(array, valueToSearch); 
    // if index is not -1 then value is present 
    if (index != -1) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Method 5: Java 8 anyMatch()

With java 8 stream you can directly get an element matching some value. For using streams, the array should be converted to a collection class.
Convert it to a java.util.List using asList() method of java.util.Arrays class.
On this list object call stream() method which returns a java.util.stream.Stream object.

Invoke anyMatch() method on this stream object. This method takes a java.util.function.Predicate object as argument.

A Predicate object can be created on the fly using java Lambda expression by writing an expression which returns a boolean value.

In the below example, the expression is s -> s.equals(valueToSearch). Here s represents the elements of array and compares them with the value we want to search in the array.
Thus, the line list.stream().anyMatch(s -> s.equals(valueToSearch)) compares the elements of the list with the value to search and returns true if any element of the list matches the string in variable valueToSearch.

import java.util.Arrays; 
import java.util.List; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodFive(); 
  } 

  static void methodFive() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "one"; 
    // convert the array to a list 
    List list = Arrays.asList(array); 
    // check if array contains value 
    boolean isFound = list.
                      stream().
                      anyMatch(s -> s.equals(valueToSearch)); 
    if (isFound) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Let’s tweak in

  1. binarySearch() method will return -1 even if the value is present in the array if the array is not sorted.
  2. binarySearch() method can also be used directly in situations when the index of the value in the array is required.
  3. Arrays.asList will throw a NullPointerException if the array supplied as argument is null.
  4. ArrayUtils from Apache Commons library also iterates over the array and compares each element with the value to search.
  5. There are different overloaded versions of contains method in ArrayUtils from Apache Commons library which act on arrays of various data types such as char, float, double, int, long, short etc.
  6. All the above methods work on string arrays but they can be used to search an element in array of other data types such as int array, char array etc.

Hope the article was useful.

Leave a Reply