This example demonstrate how to find specific items in 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[] colours = { "Red", "Orange", "Yellow", "Green",
"Blue", "Violet", "Orange", "Blue" };
// Does colours array contains the Blue colour?
boolean contains = ArrayUtils.contains(colours, "Blue");
System.out.println("Contains Blue? " + contains);
// Can you tell me the index of each colour defined bellow?
int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");
System.out.println("indexOfYellow = " + indexOfYellow);
int indexOfOrange = ArrayUtils.indexOf(colours, "Orange");
System.out.println("indexOfOrange = " + indexOfOrange);
int lastIndexOfOrange = ArrayUtils.lastIndexOf(colours, "Orange");
System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
}
}
Here are the result of the code above.
Contains Blue? true
indexOfYellow = 2
indexOfOrange = 1
lastIndexOfOrange = 6
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022