1.11. Finding Items in an Array

Problem

You need to test an array to see if it contains an element. If the array contains the element, you need the index of the matching element.

Solution

Use ArrayUtils.contains() to see if an array contains a specified element, and use ArrayUtils.indexOf( ) or ArrayUtils.lastIndexOf( ) to find the position of a matching element. The following example demonstrates the use of these three methods:

import org.apache.commons.lang.ArrayUtils;

String[] stringArray = { "Red", "Orange", "Blue", "Brown", "Red" };

boolean containsBlue = ArrayUtils.contains( stringArray, "Blue" );
int indexOfRed = ArrayUtils.indexOf( stringArray, "Red");
int lastIndexOfRed = ArrayUtils.lastIndexOf( string, "Red" );

System.out.println( "Array contains 'Blue'? " + containsBlue );
System.out.println( "Index of 'Red'? " + indexOfRed );
System.out.println( "Last Index of 'Red'? " + lastIndexOfRed );

This example locates strings in a string array and produces the following output:

Array contains 'Blue'? true
Index of 'Red'? 0
Last Index of 'Red'? 4

Discussion

All three methods work with an object array or any primitive array; in fact, almost every method defined in ArrayUtils can be applied to every possible array type—boolean[], byte[], char[], double[], float[], long[], short[], and Object[]. When using a primitive array, ArrayUtils compares the value in question to each element of an array until a match is found. When using an object array, ArrayUtils calls the equals( ) method to check for a matching array element.

ArrayUtils.indexOf( ) and ArrayUtils.lastIndexOf( ) take an optional third parameter that controls where an element search begins. In the next example, you are searching an array of double primitives for the value -9999. Example 1-7 demonstrates how to establish that the value is contained within an array and how to locate the index for each matching element.

Example 1-7. Searching an array using ArrayUtils.contains( ) and ArrayUtils.indexOf( )

// temps is a 1000 element long[]
long[] temps = readTemps( );

// Check to see if the array contains -9999
boolean hasErrorFlag = ArrayUtils.contains( temperature, -9999 );
    
// Print out the index of every errored reading
int start = 0;
while( hasErrorFlag && 
         (ArrayUtils.indexOf(temperature, -9999, start) != -1) ) {
    int errorIdx = ArrayUtils.indexOf(temperature, -9999, start);
    System.out.println( "Error reading at index: " + errorIdx );
    start = errorIdx + 1;
}

You could easily implement this method yourself; ArrayUtils.contains( ) and ArrayUtils.indexOf( ) are simply methods that iterate through every element of an array and test for equality. The simple savings you gain from ArrayUtils is one less for loop you have to test and maintain:

long testValue = -9999;
boolean hasErrors = false;

for( int i = 0; i < temps.length; i++ ) {
    if( temps[i] == testValue ) {
        hasErrors = true;
    }
}

The benefits are small, but maintaining your own custom utility classes is a pain—it is just another thing to test and maintain. ArrayUtils isn’t going to change your application’s architecture, but it will ultimately reduce the amount of trivial code you have to write, and you will not have to expend energy maintaining or testing trivial code.

See Also

Chapter 4 contains a number of recipes dealing with Predicate objects and filtering collections. Instead of using the three methods defined in this recipe, you can put objects into a collection and count or select the elements that match an EqualPredicate. See Chapter 4 for more information about querying collections with predicates.

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.