Many times developers encounter this scenario where they have an array of string values and another single string value and they may need to perform any of the following tasks :

  1. Check whether the string exists in the array or search array for the given string.
  2. If the string exists in the array, then get the index of its position in array.

This post will detail out 5 different methods to search a string in an array to check if the array contains it or not with example programs.

Method 1 : Iterating 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 StringChecker {
 
   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 data types such as int, long, float, double etc.

Method 2 : Converting array to a List
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 element.
Array is converted to a list using asList method of java.util.Arrays class. 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");
	}
    }
}

Check out different methods for conversion of array to list in java here.

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 Binary Search of Arrays class
java.util.Arrays class has a binarySearch method which searches for a value in an array using binary search algorithm.
This method takes two arguments : an array and 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 : Using anymatch in java 8
Java 8 has provided streams over data structures by which you can directly get an element matching some value. For using streams, first the array should be converted to a collection class.
We 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.
Call the 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.

To know what is a Lambda expression in java, refer this post.

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 -&gt; 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 java.lang.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, character array etc.

Liked the article!!! Why not click the clap icon 🙂

1

Mark Your Impression

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.