How to Find an Element in an Array - Java

From WikiHTP

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 the required element, or -1 if the element is not present.

Using Arrays.binarySearch (for sorted arrays only)[edit]

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

Using an Arrays.asList (for non-primitive arrays only)[edit]

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

Using a Stream[edit]

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

Linear search using a loop[edit]

  int index = -1;
  for (int i = 0; i < array.length; i++) {
      if ("A".equals(array[i])) {
          index = i;
          break;
      }            
  }
  // 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[edit]

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");


>=Java SE 8
boolean isPresent = Stream<String>.of(strings).anyMatch(x -> "A".equals(x));


boolean isPresent = false;
for (String s : strings) {
    if ("A".equals(s)) {
        isPresent = true;
        break;
    }
}

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

About This Tutorial

This page was last edited on 28 January 2019, at 06:34.