Check if an Array Contains a Value in Java (int and String)

Learn to check if an array contains a value in Java with Arrays.asList(), anyMatch(), binarySearch() and HashSet, and why asList() fails on int[].

Decision diagram for choosing how to check if a Java array contains a value

Java arrays have no contains() method, so to check if an array contains a value we either wrap an object array in a list with Arrays.asList(array).contains(value), or test a primitive array with Arrays.stream(array).anyMatch(e -> e == value). Both scan the elements from the start and stop at the first match.

We need such a check to validate input against a fixed set of allowed values, to skip duplicates before adding an item, or to find where a value sits so that we can update it. The same scan also gives us the index of the value.

The following example checks a String array and an int array, and finds the position of one tag.

String[] tags = {"java", "spring", "kafka"};
boolean hasSpring = Arrays.asList(tags).contains("spring");      // true
int kafkaAt = Arrays.asList(tags).indexOf("kafka");              // 2
int[] ports = {80, 443, 8080};
boolean hasHttps = Arrays.stream(ports).anyMatch(p -> p == 443);  // true

Notice that the object array and the primitive array need different calls. The sections cover why Arrays.asList() fails on int[], null-safe loops, searching by a condition, binary search on sorted arrays, and HashSet for repeated lookups.

1. Searching an Object Array with Arrays.asList()

Calling Arrays.asList() wraps the array in a fixed-size list without copying it. The list method contains() compares each element with equals(), and indexOf() returns the position of the first match or -1.

Decision diagram for choosing how to check if a Java array contains a value
The right call depends on the element type, whether the array is sorted, and how many lookups we make

Because the comparison uses equals(), a String built at runtime still matches a literal, and a null element or target works too. For our own classes, a contains() check finds a match only when the class overrides equals(), which a record does for us.

record Room(String type, int beds) {}
String[] tags = {"java", null, "kafka"};
boolean found = Arrays.asList(tags).contains(new String("java"));   // true
boolean hasNull = Arrays.asList(tags).contains(null);               // true
int missing = Arrays.asList(tags).indexOf("maven");                 // -1
Room[] rooms = {new Room("twin", 2), new Room("suite", 4)};
boolean hasSuite = Arrays.asList(rooms).contains(new Room("suite", 4));   // true

The shorter List.of(tags) looks similar but is not a drop-in replacement. It copies the array, rejects null elements, and its contains(null) throws an exception, so we stay with Arrays.asList() for arrays that may hold null.

String[] codes = {"a", "b"};
boolean viaListOf = List.of(codes).contains(null);   // NullPointerException

2. Why Arrays.asList() Returns false for an int Array

Calling Arrays.asList() on an int[] creates a List<int[]> with one element, the array itself, so contains() returns false for every number. Generics cannot hold primitives, so the whole int[] becomes the single T. The code compiles without a warning, which makes the bug hard to spot.

int[] ports = {80, 443, 8080};
boolean wrong = Arrays.asList(ports).contains(443);            // false
int size = Arrays.asList(ports).size();                        // 1
boolean right = Arrays.stream(ports).anyMatch(p -> p == 443);  // true
boolean boxed = Arrays.stream(ports).boxed().toList().contains(443);   // true

The stream version is the shortest fix. The anyMatch() method stops at the first match, whereas the boxed list version creates an Integer for every element before searching, which we only need when we want a list of the primitive values anyway.

The JDK has stream overloads for only three primitive array types. For the other five, we use IntStream.range() over the indexes, a String method for char[], or a plain loop.

Array typeShortest JDK check
int[], long[], double[]Arrays.stream(a).anyMatch(e -> e == v)
char[]new String(a).indexOf(v) >= 0
byte[], short[], float[]IntStream.range(0, a.length).anyMatch(i -> a[i] == v) or a loop
boolean[]A loop
Any object arrayArrays.asList(a).contains(v)
char[] grade = {'A', 'B', 'C'};
boolean hasB = new String(grade).indexOf('B') >= 0;                        // true
byte[] flags = {1, 0, 4};
boolean hasFour = IntStream.range(0, flags.length).anyMatch(i -> flags[i] == 4);   // true
double[] rates = {0.5, 1.25};
boolean hasRate = Arrays.stream(rates).anyMatch(r -> r == 1.25);           // true

3. Writing a Null-Safe contains() Method

A loop is still the clearest choice when a method must accept a null array, or when we want the index without creating a list or a stream. This scan is the linear search algorithm, so it takes O(n) time and stops at the first match.

static <T> int indexOf(T[] array, T value) {
    if (array == null) {
        return -1;
    }
    for (int i = 0; i < array.length; i++) {
        if (Objects.equals(array[i], value)) {
            return i;
        }
    }
    return -1;
}
static <T> boolean contains(T[] array, T value) {
    return indexOf(array, value) >= 0;
}
String[] beds = {"single", null, "double"};
boolean hasDouble = contains(beds, "double");   // true
int nullAt = indexOf(beds, null);              // 1
boolean none = contains(null, "single");        // false

The call Objects.equals(array[i], value) handles null on either side. A version with array[i].equals(value) throws a NullPointerException as soon as it reaches a null element. For int[], the same loop compares with ==.

4. Matching a Condition Instead of an Exact Value

Exact equality is not always the question. A search box ignores case, and a booking form needs any room with at least four beds, so we pass a condition to anyMatch(), and use IntStream.range() when we also need the index.

String[] tags = {"Java", "Spring", "Kafka"};
boolean ignoreCase = Arrays.stream(tags).anyMatch(t -> t.equalsIgnoreCase("spring"));   // true
Room[] rooms = {new Room("twin", 2), new Room("suite", 4)};
boolean family = Arrays.stream(rooms).anyMatch(r -> r.beds() >= 4);                     // true
OptionalInt firstBig = IntStream.range(0, rooms.length).filter(i -> rooms[i].beds() >= 4).findFirst();   // OptionalInt[1]

When every value from a second collection must be present, we check them together with containsAll(), which runs one search per value.

String[] tags = {"Java", "Spring", "Kafka"};
List<String> required = List.of("Java", "Kafka");
boolean all = Arrays.asList(tags).containsAll(required);   // true

5. Arrays.binarySearch() for Sorted Arrays

On a sorted array, Arrays.binarySearch() halves the search range at each step and needs O(log n) comparisons instead of O(n). It returns the index of the value, or a negative number, -(insertion point) – 1, when the value is missing.

int[] years = {2019, 2021, 2023, 2025};
int idx = Arrays.binarySearch(years, 2023);   // 2
int gap = Arrays.binarySearch(years, 2022);   // -3, would go at index 2
boolean has2022 = gap >= 0;                   // false

The result on an unsorted array is undefined, so it may report a present value as missing. Sorting first costs O(n log n) and reorders the caller’s array, which is cheaper than repeated linear scans only when we search the same array many times. The Java array sorting tutorial covers Arrays.sort() and its variants.

int[] codes = {40, 10, 30, 20};
int unsorted = Arrays.binarySearch(codes, 40);   // -5, wrong, 40 is at index 0
int[] sorted = codes.clone();
Arrays.sort(sorted);
int ok = Arrays.binarySearch(sorted, 40);        // 3

6. Many Lookups Against the Same Array

An upload service that checks every file against a list of allowed extensions makes thousands of lookups against the same small array. Each array scan is O(n), whereas a HashSet built once answers each lookup in O(1) time on average, so we convert the array a single time and keep the set.

String[] allowed = {"png", "jpg", "pdf", "png"};
Set<String> allowedSet = new HashSet<>(Arrays.asList(allowed));
boolean okPdf = allowedSet.contains("pdf");   // true
boolean okExe = allowedSet.contains("exe");   // false

The HashSet constructor accepts duplicates and null. The factory Set.of(allowed) throws an IllegalArgumentException for the duplicate png, and Set.copyOf() accepts duplicates but rejects null.

String[] allowed = {"png", "jpg", "pdf", "png"};
Set<String> strict = Set.of(allowed);   // IllegalArgumentException: duplicate element: png

Projects that already use Apache Commons Lang can call ArrayUtils.contains(), which has overloads for every primitive array type, returns false for a null array, and has a matching indexOf().

int[] ports = {80, 443, 8080};
boolean viaCommons = ArrayUtils.contains(ports, 8080);   // true
boolean nullArray = ArrayUtils.contains((int[]) null, 80);   // false

7. Choosing How to Check if an Array Contains a Value

Most code needs one of the first two rows. The others pay off only with sorted data, repeated lookups or a library that is already on the classpath.

SituationMethodTime per lookup
Object array, one-off checkArrays.asList(a).contains(v)O(n)
Primitive array, one-off checkArrays.stream(a).anyMatch(e -> e == v)O(n)
Need the indexindexOf() or IntStream.range() with filter()O(n)
Condition such as ignore caseanyMatch(predicate)O(n)
Sorted arrayArrays.binarySearch()O(log n)
Many lookups, same dataHashSet built onceO(1) on average
Commons Lang on the classpathArrayUtils.contains()O(n)

8. Array Contains FAQs

Developers searching for an array contains method also ask these questions.

8.1. Is there a contains() method for arrays in Java?

No. Arrays have only the length field and the methods inherited from Object. We use Arrays.asList(array).contains() for object arrays, anyMatch() for primitive arrays, or ArrayUtils.contains() from Apache Commons Lang.

8.2. How do we check if an array contains a value ignoring case?

We stream the array and compare with equalsIgnoreCase(), as in Arrays.stream(tags).anyMatch(t -> t.equalsIgnoreCase(“spring”)). For many lookups, we put the lowercase values into a HashSet and lowercase the target before each check.

8.3. How do we check if an array contains all the values of another array?

We call Arrays.asList(first).containsAll(Arrays.asList(second)). For large arrays, we copy the first array into a HashSet, because containsAll() on a list runs a full scan for each value. Finding the common values themselves is covered in the array intersection tutorial.

8.4. How do we find the index of an element in an array?

For object arrays, Arrays.asList(array).indexOf(value) returns the first index or -1, and lastIndexOf() returns the last one. For primitive arrays, we use IntStream.range(0, a.length).filter(i -> a[i] == v).findFirst(), which returns an OptionalInt.

8.5. Does contains() work for an array of custom objects?

Yes, if the class overrides equals(). Without an override, equals() compares references, so only the same object matches. Records, String and the wrapper classes already compare by value.

9. Conclusion

Java arrays do not have a contains() method. For object arrays, Arrays.asList(array).contains() and indexOf() do the job with equals() semantics and handle null.

For int[], long[] and double[], we use Arrays.stream() with anyMatch(), because Arrays.asList() on a primitive array wraps the whole array as one element and always returns false. Sorted arrays can use Arrays.binarySearch(), and repeated lookups belong in a HashSet.

10. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.