Check if an Array contains a certain value

In this post we will provide an example to check if an array contains a certain value. Below is two examples one using Java8 and the pre Java 8.

Check if an Array contains a certain value

Java 8 Example:

The example below uses the Arrays.stream() method to convert the array to a streams object. This allows us to use the anyMatch() method to determine if the array contains a certain value.

Running the above example produces the following output:

Pre Java 8 Example:

The next example is similar to the one above however, if you are not using Java then Streams is not available. The alternative approach is to use asLists() and then use the contains() method.

Running the above example produces the following output:

Similar posts:

  1. How to sort an Array in Java
  2. Java 8 Stream Map example
  3. Java 8 allMatch, noneMatch and anyMatch examples
  4. Convert String to InputStream in Java

References:

  1. Java 8 Arrays API Documentation

Leave a Reply