Finding an element in an array

suggest change

There are many ways find the location of a value in an array. The following example snippets all assume that the array is one of the following:

String[] strings = new String[] { "A", "B", "C" };
int[] ints = new int[] { 1, 2, 3, 4 };

In addition, each one sets index or index2 to either the index of required element, or -1 if the element is not present.

Using Arrays.binarySearch (for sorted arrays only)

int index = Arrays.binarySearch(strings, "A");
int index2 = Arrays.binarySearch(ints, 1);

Using a Arrays.asList (for non-primitive arrays only)

int index = Arrays.asList(strings).indexOf("A");
int index2 = Arrays.asList(ints).indexOf(1);  // compilation error

Using a Stream

int index = IntStream.range(0, strings.length)
                     .filter(i -> "A".equals(strings[i]))
                     .orElse(-1); // If not present, gives us -1.
// Similar for an array of primitives

Linear search using a loop

int index = -1;
for (int i = 0; i < array.length; i++) {
    if ("A".equals(array[i])) {
        index = i;
// Similar for an array of primitives

Linear search using 3rd-party libraries such as org.apache.commons

int index = org.apache.commons.lang3.ArrayUtils.contains(strings, "A");
int index2 = org.apache.commons.lang3.ArrayUtils.contains(ints, 1);

Note: Using a direct linear search is more efficient than wrapping in a list.

Testing if an array contains an element

The examples above can be adapted to test if the array contains an element by simply testing to see if the index computed is greater or equal to zero.

Alternatively, there are also some more concise variations:

boolean isPresent = Arrays.asList(strings).contains("A");
boolean isPresent = Stream<String>.of(strings).anyMatch(x -> "A".equals(x));
boolean isPresent = false;
for (String s : strings) {
    if ("A".equals(s)) {
        isPresent = true;

boolean isPresent = org.apache.commons.lang3.ArrayUtils.contains(ints, 4);

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents