Grails Cookbook - A collection of tutorials and examples

Check If String Array Contains a Value In Java

Arrays are very useful when we need to work with multiple values of the same type. For example, we may need multiple instances of Strings. Arrays provide a data structure that is easy to learn and use. But since arrays are simple, it does not have much methods for some operations we may need. Below are examples on how to test or check if a String Array contains a certain value in Java.

Check Using Custom Code

The simplest way to find out if a String Array contains a certain value is to loop through all the items and test one by one. Below is a simple example:
String[] myStringArray = {"Car", "Plane", "Bike", "Train"};
String stringToLocate= "Bike";
boolean found = false;
for (String element:myStringArray ) {
    if ( element.equals( stringToLocate)) {
        found = true;
        System.out.println( "The value is found!");
    }
}
if (!found) {
    System.out.println( "The value is not found!" );
}

A small pitfall we need to be careful about is to use the equals method and not the == operator. The code will output:

The value is found!

We may refactor it to be a function, for example:

public static boolean checkIfExists(String[] myStringArray, String stringToLocate) {
    for (String element:myStringArray ) {
        if ( element.equals( stringToLocate)) {
            return true;
        }
    }
    return false;
}
public static void main( String[] args )
{
    boolean found =  checkIfExists(new String[] {"Car", "Plane", "Bike", "Train"}, "Bike");
    if (found) {
        System.out.println( "The value is found!" );
    } else {
        System.out.println( "The value is not found!" );
    }
}

Check by Converting to List

Another way of testing or checking if a String Array contains a specific value in Java is to convert the data structure into a list. Below is an example of converting the code above:

String[] myStringArray = {"Car", "Plane", "Bike", "Train"};
boolean found = Arrays.asList( myStringArray ).contains( "Bike" );
if (found) {
    System.out.println( "The value is found!" );
} else {
    System.out.println( "The value is not found!" );
}

And converting to a function makes it much shorter

public static boolean checkIfExists(String[] myStringArray, String stringToLocate) {
    return Arrays.asList( myStringArray ).contains( stringToLocate );
}
public static void main( String[] args )
{
    boolean found =  checkIfExists(new String[] {"Car", "Plane", "Bike", "Train"}, "Bike");
    if (found) {
        System.out.println( "The value is found!" );
    } else {
        System.out.println( "The value is not found!" );
    }
}