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
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.
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.
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.
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.
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.
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.