This example demonstrates how to find specific items in an array. We will use the org.apache.commons.lang3.ArrayUtils
class. This class provides method called contains(Object[] array, Object objectToFind)
method to check if an array contains the objectToFind
in it.
We can also use the indexOf(Object[] array, Object objectToFind)
method and the lastIndexOf(Object[] array, Object objectToFind)
method to get the index of an array element where our objectToFind
is located.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayUtilsIndexOfDemo {
public static void main(String[] args) {
String[] colors = { "Red", "Orange", "Yellow", "Green",
"Blue", "Violet", "Orange", "Blue" };
// Does the "colors" array contain the Blue color?
boolean contains = ArrayUtils.contains(colors, "Blue");
System.out.println("Contains Blue? " + contains);
// Can you tell me the index of each color defined bellow?
int indexOfYellow = ArrayUtils.indexOf(colors, "Yellow");
System.out.println("indexOfYellow = " + indexOfYellow);
int indexOfOrange = ArrayUtils.indexOf(colors, "Orange");
System.out.println("indexOfOrange = " + indexOfOrange);
int lastIndexOfOrange = ArrayUtils.lastIndexOf(colors, "Orange");
System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
}
}
Here are the results of the code above.
Contains Blue? true
indexOfYellow = 2
indexOfOrange = 1
lastIndexOfOrange = 6
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024