How do I find items in an array?
Category: Commons Lang, viewed: 1803 time(s).
This example demonstrate how to find items in array. We use the ArrayUtils class. This class provides method such as contains(Object[] array, Object objectToFind) to check if the array contains some value. We can also use the indexOf(Object[] array, Object objectToFind) and lastIndexOf(Object[] array, Object objectToFind) methods to gen the index of array where our object is located.
package org.kodejava.example.commons.lang; import org.apache.commons.lang.ArrayUtils; public class ArrayUtilsIndexOf { 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
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I find text between two strings?
- How do I check for an empty string?
- How do I get the nearest hour, minute, second of a date?
- How do I format date and time using DateFormatUtils class?
- How do I use CompareToBuilder class?
- How do I use ReflectionToStringBuilder class?
- How do I convert array of object to array of primitive?
- How do I convert an array to a Map?
- How do I reverse array elements order?
- How do I count word occurrences in a string?