Java example

How to check if an array contains a value in Java

6 min read Updated Sep 2026 Runs in an isolated runtime
Quick answer

Arrays have no contains() method, so wrap the array in a list: Arrays.asList(array).contains(value). That works for object arrays such as String[] and Integer[]. For a primitive int[], use Arrays.stream(array).anyMatch(n -> n == value), because Arrays.asList(int[]) silently gives the wrong answer.

A Java array is a fixed block of values with a length and nothing else: no contains(), no indexOf(). The collections framework has both, so the usual answer is to view the array as a List for a moment. That trick only works for arrays of objects, which is why primitive arrays need a stream or a loop, and why the difference between equals() and == keeps coming up. This page covers each case, then what to use when you check many values against the same array. Each example runs on this page: hit Run, then edit the code and run it again.

1Arrays.asList(array).contains()Recommended

Arrays.asList(array) returns a fixed-size List backed by the array itself. Nothing is copied, so creating it is cheap, and you get the list's contains() and indexOf() for free. Both compare with equals(), so two strings with the same text match even when they are different objects. This is the one-line answer for String[], Integer[] and any other array of objects, and it works on every Java version.

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "cherry"};

        System.out.println(Arrays.asList(fruits).contains("banana"));
        System.out.println(Arrays.asList(fruits).contains("mango"));

        // Any object array works: Integer, Double, records, your own classes
        Integer[] primes = {2, 3, 5, 7, 11};
        if (Arrays.asList(primes).contains(7)) {
            System.out.println("7 is prime");
        }

        // Need the position as well? indexOf returns it, or -1
        System.out.println(Arrays.asList(fruits).indexOf("cherry"));

        // Arrays.asList is fine with null elements and a null search value
        String[] withGap = {"a", null, "c"};
        System.out.println(Arrays.asList(withGap).contains(null));
    }
}

Output

Prints true, false, 7 is prime, 2, then true. contains() still scans the elements one by one, so each call costs time proportional to the array's length. Since Java 9, List.of(array) reads much the same, but it copies the array and throws NullPointerException on null elements (see the FAQ). For more ways to turn an array into a collection, see convert an array to a list.

2Primitive arrays: Arrays.stream().anyMatch()

Arrays.asList() takes a varargs T..., and a type parameter can't be a primitive. Pass it an int[] and T becomes int[]: you get a List<int[]> holding one element, the whole array. It compiles, it runs, and contains() returns false for every number. The Java 8+ answer for int[], long[] and double[] is a stream: Arrays.stream(array).anyMatch(test) returns true at the first element the test passes for.

Main.java
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 88, 95, 61};

        // Stream the int[] and test each element; stops at the first match
        System.out.println(Arrays.stream(scores).anyMatch(s -> s == 95));
        System.out.println(Arrays.stream(scores).anyMatch(s -> s == 100));

        // Any condition works, not just equality
        System.out.println(Arrays.stream(scores).anyMatch(s -> s < 65));

        // The trap: Arrays.asList(int[]) is a list with ONE element, the array itself
        List<int[]> wrong = Arrays.asList(scores);
        System.out.println(wrong.size());
        System.out.println(Arrays.asList(scores).contains(95));

        // A boxed Integer[] is an object array, so asList works on it
        Integer[] boxed = {72, 88, 95, 61};
        System.out.println(Arrays.asList(boxed).contains(95));
    }
}

Output

Prints true, false, true, then 1 and false for the trap, then true for the Integer[]. The stream version needs no boxing and takes any condition, such as the s < 65 test above. Arrays.stream() only has overloads for int[], long[] and double[]; for char[], byte[], short[], float[] or boolean[], use the loop in the next section.

3A plain loop, and equals() vs ==

A for loop that returns early on a match works on every array type and every Java version, and it is what the library methods do internally. The one decision is how to compare. For primitives, == compares values and is right. For objects, == asks whether two references point at the same object, which is not what you mean: a string read from input is a different object from the one in your array, even with identical text. Compare objects with equals(), and use Objects.equals(a, b) (Java 7+) when either side can be null.

Main.java
import java.util.Objects;

public class Main {
    // Primitives: compare with ==
    static boolean contains(int[] array, int target) {
        for (int value : array) {
            if (value == target) {
                return true;
            }
        }
        return false;
    }

    // Objects: compare with equals, here via the null-safe Objects.equals
    static boolean contains(String[] array, String target) {
        for (String value : array) {
            if (Objects.equals(value, target)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] ids = {4, 8, 15, 16, 23, 42};
        System.out.println(contains(ids, 15));
        System.out.println(contains(ids, 99));

        String[] names = {"Ada", null, "Linus"};

        // A String built at runtime (like user input) is a separate object
        String typed = new String("Linus");
        System.out.println(typed == names[2]);
        System.out.println(typed.equals(names[2]));

        // Objects.equals compares text and copes with the null element
        System.out.println(contains(names, typed));
        System.out.println(contains(names, null));
        System.out.println(contains(names, "Grace"));
    }
}

Output

Prints true, false, then false for == and true for equals(), then true, true, false. Writing value.equals(target) in the loop would throw NullPointerException on the null element; Objects.equals() handles both sides being null. The == check on strings sometimes appears to work because identical string literals share one object, which is exactly why the bug slips through testing. See compare strings in Java for the full story.

4Arrays of objects: match on a field

With an array of your own objects, the question is usually "is there a user with id 2?", not "is this exact object here?". Stream the array and test the field with anyMatch(). Whole-object contains() only works when the class defines equals(). A record (Java 16+) gets one automatically from its fields; a plain class inherits Object.equals(), which compares identity, so an equal-looking object is never found.

Main.java
import java.util.Arrays;

public class Main {
    record User(int id, String name, String role) {}

    // A plain class that does not override equals() is compared by identity
    static class Account {
        final String email;

        Account(String email) {
            this.email = email;
        }
    }

    public static void main(String[] args) {
        User[] users = {
            new User(1, "Ada", "admin"),
            new User(2, "Linus", "user"),
        };

        // Test one field with anyMatch
        System.out.println(Arrays.stream(users).anyMatch(u -> u.id() == 2));
        System.out.println(Arrays.stream(users).anyMatch(u -> u.role().equals("owner")));

        // Records get equals() from their fields, so contains() matches a look-alike
        System.out.println(Arrays.asList(users).contains(new User(2, "Linus", "user")));

        // Without equals(), a look-alike is a different object and is not found
        Account[] accounts = {new Account("[email protected]")};
        System.out.println(Arrays.asList(accounts).contains(new Account("[email protected]")));
        System.out.println(Arrays.stream(accounts).anyMatch(a -> a.email.equals("[email protected]")));

        // Case-insensitive match on a String array
        String[] tags = {"Java", "Kotlin", "Scala"};
        System.out.println(Arrays.stream(tags).anyMatch(t -> t.equalsIgnoreCase("JAVA")));
    }
}

Output

Prints true, false, true, false, true, true. The Account line is the classic surprise: the object is "clearly there" but contains() says false. Either test a field with anyMatch(), or give the class equals() and hashCode() (or make it a record). If you need the matching object rather than a yes or no, swap anyMatch(test) for filter(test).findFirst(), which returns an Optional.

5Which should you use?

MethodWorks onCost per checkBest for
Arrays.asList(arr).contains(v)Object arrays onlyScans the arrayString[], Integer[], records: the default
Arrays.stream(arr).anyMatch(test)int[], long[], double[], objectsScans the arrayPrimitive arrays, conditions, a field of an object
for loopEvery array typeScans the arraychar[] and byte[], hot paths, pre-Java 8 code
Arrays.binarySearch(arr, v)Sorted arrays onlyHalves the range each stepLarge arrays that are already sorted
set.contains(v)A Set built onceHash lookupMany lookups against the same values

6Many lookups? Use a HashSet, or binarySearch on sorted data

Every method above walks the array, which is fine for one check and adds up when you test hundreds of values against the same array in a loop. Copy the array into a HashSet once and each contains() after that is a hash lookup that takes about the same time however big the set is. If the array is already sorted, Arrays.binarySearch() finds a value without the extra memory. It returns the index when found and a negative number when not, and it gives no reliable answer on an unsorted array.

Main.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        String[] blocked = {"spam.com", "junk.net", "bad.org"};

        // Build the Set once: one pass over the array
        Set<String> blockedSet = new HashSet<>(Arrays.asList(blocked));

        // Every contains() after that is a hash lookup, not a scan
        for (String domain : List.of("mail.com", "junk.net")) {
            System.out.println(domain + (blockedSet.contains(domain) ? " is blocked" : " is fine"));
        }

        // Already sorted? Arrays.binarySearch halves the range each step
        int[] sorted = {3, 8, 15, 21, 42};
        System.out.println(Arrays.binarySearch(sorted, 21));
        System.out.println(Arrays.binarySearch(sorted, 5));
        System.out.println(Arrays.binarySearch(sorted, 5) >= 0);

        // The trap: on an unsorted array it can miss a value that is there
        int[] unsorted = {42, 8, 21, 3, 15};
        System.out.println(Arrays.binarySearch(unsorted, 42));

        // Sort a copy first (clone keeps the original order intact)
        int[] copy = unsorted.clone();
        Arrays.sort(copy);
        System.out.println(Arrays.binarySearch(copy, 42) >= 0);
    }
}

Output

Prints mail.com is fine, junk.net is blocked, 3, -2, false, -6, then true. The -2 encodes where 5 would be inserted (-(insertion point) - 1), so always test >= 0 rather than comparing with -1. The -6 is the trap: 42 sits at index 0 of the unsorted array, but binary search never looks there. Sorting costs more than one linear scan, so only sort for binary search when you will search many times. HashSet iteration order is unspecified, which doesn't matter for contains().

Frequently asked questions

Why does Arrays.asList(intArray).contains(x) always return false?

Because generics can't hold primitives. Arrays.asList(int[]) treats the whole array as a single element and returns a List<int[]> of size 1, so contains(95) compares 95 against the array object and is false. Use Arrays.stream(array).anyMatch(n -> n == 95), a loop, or store the numbers in an Integer[].

Can I use List.of(array).contains(value) instead?

On Java 9+ it works for object arrays, with two catches. List.of(array) copies the array, and it throws NullPointerException if any element is null. Calling contains(null) on it throws NullPointerException too. Arrays.asList(array) has neither problem and copies nothing, so it remains the better choice for a quick membership check.

How do I check if a char[] contains a character?

There is no Arrays.stream(char[]), so either write a loop comparing with ==, or turn the array into a String and search it: String.valueOf(chars).indexOf('o') >= 0. The same loop works for byte[], short[], float[] and boolean[].

Why does contains() return false for an object that is in the array?

Because contains() uses equals(), and a class that does not override it inherits identity comparison from Object: a new object with the same field values is a different object. Override equals() and hashCode(), declare the type as a record (Java 16+), or test a field with Arrays.stream(array).anyMatch(a -> a.email.equals(target)).

How do I check if an array contains all or any of several values?

Wrap it once with List<String> list = Arrays.asList(array). For "all of these", use list.containsAll(List.of("read", "write")). For "any of these", use !Collections.disjoint(list, List.of("delete", "share")), since disjoint() returns true only when the two collections share no element.

Is there a built-in ArrayUtils.contains() in Java?

Not in the standard library. Apache Commons Lang has ArrayUtils.contains() and Guava has Ints.contains() and friends, and they are handy if a project already depends on them. In plain Java SE, Arrays.asList(array).contains(value) for object arrays and Arrays.stream(array).anyMatch(...) for primitives cover the same ground in one line.

Run it yourself

Open any of these in the full Java editor: tweak, run, and share.

Java playground