Find element in array

In this example we will search for specified object in a given array while using java, guava and apache commons. Since we are huge fans of the Minnesota Vikings, not, we will highlight losings seasons and check if a specified value exists.

Straight up Java

With straight up java, there are multiple ways to find an element in an array. We will first iterate over an array with a java 5 for each loop comparing each element to 1962. If 1962 is found, we will set the losingSeason boolean variable to false and proceed to break the loop.

Loop

@Test
public void search_array_java () {

    Integer[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    boolean losingSeason = false;
    for (Integer number : vikQueensLosingSeasons) {
        if (number.equals(1962)) {
            losingSeason = true;
            break;
        }
    }

    assertTrue(losingSeason);
}

List contains

Similar to how we find an element in a collection we will convert the array to a list and then call Lists.contains to check if the list contains the specified element.

@Test
public void search_array_java_with_list_contains_with_list_contains () {

    Integer[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    boolean hadALosingSeason = Arrays
            .asList(vikQueensLosingSeasons)
            .contains(new Integer(1962));

    assertTrue(hadALosingSeason);
}

Binary search

Another technique is to use Arrays.binarySearch to find an element in an array by using the binary search algorithm. When using this technique, you must sort array in ascending order according to the natural ordering of its elements.

@Test
public void array_contains_element_java_binary_search () {

    Integer[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    Arrays.sort(vikQueensLosingSeasons);

    int elementPosition = Arrays.binarySearch(vikQueensLosingSeasons, 1962);

    assertTrue(elementPosition >= 0);
}

Java 8

Using java 8 we will build a stream from an array using Arrays.stream, them filter the stream with criteria to find an element in an array. Next we will call the Stream.findAny method which will return an Optional describing the element if found otherwise an empty Optional if the stream is empty.

@Test
public void array_contains_element_java8 () {

    Integer[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    java.util.Optional<Integer> yearExists =
            Arrays.stream(vikQueensLosingSeasons)
            .filter(p -> p == 1972)
            .findAny();

    assertTrue(yearExists.isPresent());
}

Google Guava

Primitive contains

Ints is class in the guava library that contains a series of static methods pertaining to int primitives. In the example below, we will call Int.contains on the vikQueensLosingSeasons to verify that 1972 exists.

@Test
public void array_contains_element_java_with_guava () {

    int[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    boolean yearExists = Ints.contains(vikQueensLosingSeasons, 1972);

    assertTrue(yearExists);
}

Iterator.tryfind w/ predicate

Guava Iterables utilty class provides Iterables.tryFind method which returns a guava Optional class containing the first element in the array that satisified the given predicate. If an element doesn't exists it will return an empty Optional.

@Test
public void find_element_in_array_java_with_guava() {

    Integer[] vikQueensLosingSeasons = { 1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979,
            1981, 1985 };

    Optional<Integer> contains = Iterators.tryFind(
            Iterators.forArray(vikQueensLosingSeasons),
            new Predicate<Integer>() {

                public boolean apply(Integer input) {
                    if (input == 1962) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });

    assertTrue(contains.isPresent());
    assertEquals(new Integer(1962), contains.get());
}

Apache Commons

Apache commons ArrayUtils class provides operations for dealing with primitive arrays. The ArrayUtils.contains method will check if the value is in the given array.

@Test
public void array_contains_element_java_with_apache_commons () {

    int[] vikQueensLosingSeasons = {
            1962, 1967, 1984, 2011, 1966,
            1963, 1982, 2001, 1990, 2002,
            2006, 2010, 1965, 1972, 1979,
            1981, 1985};

    boolean losingSeason = ArrayUtils.contains(vikQueensLosingSeasons, 1962);
    assertTrue(losingSeason);
}