Check if Array contains a value in Java

Often we have a requirement to check if array contains a value in Java. 

Let’s say we need to check if our array of strings contains the word “Java”. We can do that in the following ways:

  • Using the for-loop
  • With the Java 8 Streams
  • Using ArrayUtils class

Check if Array contains a value in Java using the for-loop

In this way, we are implementing our logic to check if array contains a particular value, which is, in our case, the word “Java”.

Example

class CheckIfArrayContainsValue {

  public static void main(String[] args) {

    String[] programmingLanguages = {"Python", "Kotlin", "Ruby", "JavaScript", "C#", "Java", "Flutter"};

    for (String lang : programmingLanguages) {
      if (lang.equals("Java")) {
        System.out.println("It does contain!");
        break; // value found, exit the loop
      }
    }

  }
}
Output: It does contain!
 
Here, we are iterating over the array, and we are checking if any of the elements are equal to “Java”. When the value is found, we break out of the loop using the break keyword.

With the Java 8 Streams

We can leverage the Streams API introduced in Java 8 to check if any element from the array matches the given word.

Example

class CheckIfArrayContainsValue {

  public static void main(String[] args) {

    String[] programmingLanguages = {"Python", "Kotlin", "Ruby", "JavaScript", "C#", "Java", "Flutter"};

    boolean contains = Arrays.stream(programmingLanguages).anyMatch("Java"::equals);

    if (contains) {
      System.out.println("It does contain!");
    } else {
      System.out.println("It doesn't contain the element!");
    }
 
  }
}
Output: It does contain!

Using the ArrayUtils class

The ArrayUtils class belongs to the Apache Commons library. It has a method contains(Object[] objectArray, Object objectToFind) that is checking if the provided array contains a particular value.

To use it, we need to add the following Maven dependency into the pom.xml:

<dependency>
    <groupid>org.apache.commons</groupid>
    <artifactid>commons-lang3</artifactid>
    <version>3.12.0</version>
</dependency>


Example

class CheckIfArrayContainsValue {

public class DemoApplication {

  public static void main(String[] args) {

    String[] programmingLanguages = {"Python", "Kotlin", "Ruby", "JavaScript", "C#", "Java", "Flutter"};

    if (ArrayUtils.contains(programmingLanguages, "Java")) {
      System.out.println("It does contain!");
    } else {
      System.out.println("It doesn't contain the value!");
    }
  }
}

}
Output: It does contain!

Leave a Reply

Your email address will not be published.