How can I verify that an array of strings contain a certain string? [duplicate] How can I verify that an array of strings contain a certain string? [duplicate] arrays arrays

How can I verify that an array of strings contain a certain string? [duplicate]


Convert the array of valid directions to a list:

List valid = Arrays.asList(directions)

Or just declare it directly as:

List valid = Arrays.asList("UP", "DOWN", "RIGHT", "LEFT", "up", "down", "right", "left")

You can then use the contains method:

if (valid.contains(input)) {    // is valid} else {    // not valid}

Note that this won't match a mixed case input such as "Up" so you might want to store just the uppercase values in the list and then use valid.contains(input.toUpperCase())


Convert your array to a List and than use the contains method.

List mylist = Arrays.asList(directions);mylist.contains(input);

The contains method returns:

true if the list contains the specified element.


Unfortunately, Java does not have an Arrays.indexOf() method. Your best bet is to write a little utility to do a simple linear search. Or you could convert to an ArrayList (see Arrays.asList()) and call indexOf() or contains().

If the array is large and speed is a concern, you could sort the array, and then use Arrays.binarySearch().