Java - search a string in string array

This code will work for you:

bool count = false;
for(int i = 0; i < array.length; i++)
{
    if(array[i].equals(x))
    {
        count = true;
        break;
    }
}
if(count)
{
    //do some other thing
}
else
{
    //do some other thing
}

You could also use the commons-lang library from Apache which provides the much appreciated method contains.

import org.apache.commons.lang.ArrayUtils;

public class CommonsLangContainsDemo {

    public static void execute(String[] strings, String searchString) {
        if (ArrayUtils.contains(strings, searchString)) {
            System.out.println("contains.");
        } else {
            System.out.println("does not contain.");
        }
    }

    public static void main(String[] args) {
        execute(new String[] { "AA","BB","CC" }, "BB");
    }

}

Do something like:

Arrays.asList(array).contains(x);

since that return true if the String x is present in the array (now converted into a list...)

Example:

if(Arrays.asList(myArray).contains(x)){
    // is present ... :)
}

since Java8 there is a way using streams to find that:

boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
    // is present ... :)
}

Tags:

Java

Arrays