Close

Java - How to find if an array contains a given value?

[Last Updated: May 18, 2018]

Java Arrays Java 

Following example shows how to find whether a provided value is contained by an array:

package com.logicbig.example;

import java.util.Arrays;

public class ArrayContains {

  public static <T> boolean contains(T[] input, T element) {
      if (input == null) {
          return false;
      }
      return Arrays.stream(input)
                   .anyMatch(e -> e == null && element == null ||
                           (e != null && e.equals(element)));
  }

  public static void main(String[] args) {
      String[] arr = {"one", "two", "three", null};

      boolean b = contains(arr, "two");
      System.out.println(b);

      b = contains(arr, null);
      System.out.println(b);

      b = contains(arr, "four");
      System.out.println(b);
  }
}
true
true
false

See Also