- Find element in array
- Straight up Java
- Loop
- List contains
- Binary search
- Java 8
- Google Guava
- Primitive contains
- Iterator.tryfind w/ predicate
- Apache Commons
- Java: Check if Array Contains Value or Element
- Arrays.asList().contains()
- Using a for-loop
- Collections.binarySearch()
- Free eBook: Git Essentials
- Java 8 Stream API
- Apache Commons — ArrayUtils
- Conclusion
- Check if Array Contains an Item in Java
Find element in array
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
@Test public void search_array_java () Integer[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean losingSeason = false; for (Integer number : vikQueensLosingSeasons) if (number.equals(1962)) losingSeason = true; break; > > assertTrue(losingSeason); >
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.
@Test public void search_array_java_with_list_contains_with_list_contains () Integer[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean hadALosingSeason = Arrays .asList(vikQueensLosingSeasons) .contains(new Integer(1962)); assertTrue(hadALosingSeason); >
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.
@Test public void array_contains_element_java_binary_search () Integer[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; Arrays.sort(vikQueensLosingSeasons); int elementPosition = Arrays.binarySearch(vikQueensLosingSeasons, 1962); assertTrue(elementPosition >= 0); >
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.
@Test public void array_contains_element_java8 () Integer[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; java.util.OptionalInteger> yearExists = Arrays.stream(vikQueensLosingSeasons) .filter(p -> p == 1972) .findAny(); assertTrue(yearExists.isPresent()); >
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.
@Test public void array_contains_element_java_with_guava () int[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean yearExists = Ints.contains(vikQueensLosingSeasons, 1972); assertTrue(yearExists); >
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.
@Test public void find_element_in_array_java_with_guava() Integer[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985 >; OptionalInteger> contains = Iterators.tryFind( Iterators.forArray(vikQueensLosingSeasons), new PredicateInteger>() public boolean apply(Integer input) if (input == 1962) return true; > else return false; > > >); assertTrue(contains.isPresent()); assertEquals(new Integer(1962), contains.get()); >
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.
@Test public void array_contains_element_java_with_apache_commons () int[] vikQueensLosingSeasons = 1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean losingSeason = ArrayUtils.contains(vikQueensLosingSeasons, 1962); assertTrue(losingSeason); >
Find element in array posted by Justin Musgrove on 14 January 2014
Tagged: java and java-arrays
Java: Check if Array Contains Value or Element
Whether in Java, or any other programming language, it is a common occurrence to check if an array contains a value. This is one of the things that most beginners tend to learn, and it is a useful thing to know in general.
In this article, we’ll take a look at how to check if an array contains a value or element in Java.
Arrays.asList().contains()
This is perhaps the most common way of solving this problem, just because it performs really well and is easy to implement.
First, we convert the array to an ArrayList . There are various ways to convert a Java array to an ArrayList, though, we’ll be using the most widely used approach.
Then, we can use the contains() method on the resulting ArrayList , which returns a boolean signifying if the list contains the element we’ve passed to it or not.
Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(intList.contains(12)); System.out.println(nameList.contains("John"));
Running this code results in:
Using a for-loop
A more basic and manual approach to solving the problem is by using a for loop. In worst case, it’ll iterate the entire array once, checking if the element is present.
Let’s start out with primitive integers first:
int[] intArray = new int[]1, 2, 3, 4, 5>; boolean found = false; int searchedValue = 2; for(int x : intArray)< if(x == searchedValue)< found = true; break; > > System.out.println(found);
The found variable is initially set to false because the only way to return true would be to find the element and explicitly assign a new value to the boolean. Here, we simply compare each element of the array to the value we’re searching for, and return true if they match:
For Strings, and custom Objects you might have in your code, you’d be using a different comparison operator. Assuming you’ve validly ovverriden the equals() method, you can use it to check if an object is equal to another, returning true if they are:
String[] stringArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; boolean found = false; String searchedValue = "Michael"; for(String x : stringArray)< if(x.equals(searchedValue))< found = true; break; > > System.out.println(found);
Running this code will result in:
Collections.binarySearch()
Additionally, we can find a specific value using a built-in method binarySearch() from the Collections class. The problem with binary search is that it requires our array be sorted. If our array is sorted though, binarySearch() outperforms both the Arrays.asList().contains() and the for-loop approaches.
If it’s not sorted, the added time required to sort the array might make this approach less favorable, depending on the size of the array and the sorting algorithm used to sort it.
binarySearch() has many overloaded variants depending on the types used and our own requirements, but the most general one is:
public static int binarySearch(Object[] a, Object[] key)
Where a represents the array, and key the specified value we’re looking for.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Now, the return value might be a bit confusing, so it’s best to take Oracle’s official documentation in mind:
The return value of this method is the index of the searched key, if it is contained in the array; otherwise (-(insertion point) — 1), where insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.
Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"Bill", "Connor", "Joe", "John", "Mark">; // Array is already sorted lexicographically List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(Collections.binarySearch(intList, 2)); System.out.println(Collections.binarySearch(nameList, "Robin"));
The first element is found, at position 1 . The second element isn’t found, and would be inserted at position 5 — at the end of the array. The return value is -(insertion point)-1 , so the return value ends up being -6 .
If the value is above equal to, or above 0 , the array contains the element, and it doesn’t contain it otherwise.
Java 8 Stream API
The Java 8 Stream API is very versatile and offers for concise solutions to various tasks related to processing collections of objects. Using Streams for this type of task is natural and intuitive for most.
Let’s take a look at how we can use the Stream API to check if an array contains an integer:
Integer[] arr = new Integer[]1, 2, 3, 4, 5>; System.out.println(Arrays.stream(arr).anyMatch(x -> x == 3));
And to do this with Strings or custom objects:
String[] arr = new String[]"John", "Mark", "Joe", "Bill", "Connor">; String searchString = "Michael"; boolean doesContain = Arrays.stream(arr) .anyMatch(x -> x.equals(searchString)); System.out.println(doesContain);
Or, you can make this shorter by using a method reference:
boolean doesContain = Arrays.stream(arr) .anyMatch(searchString::equals); System.out.println(doesContain);
Both of these would output:
Apache Commons — ArrayUtils
The Apache Commons library provides many new interfaces, implementations and classes that expand on the core Java Framework, and is present in many projects.
The ArrayUtils class introduces many methods for manipulating arrays, including the contains() method:
Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; System.out.println(ArrayUtils.contains(intArray, 3)); System.out.println(ArrayUtils.contains(nameArray, "John"));
Conclusion
In this article, we’ve gone over several ways to check whether an array in Java contains a certain element or value. We’ve gone over converting the array to a list and calling the contains() method, using a for-loop, the Java 8 Stream API, as well as Apache Commons.
Check if Array Contains an Item in Java
Learn to check if an array contains an element. Also, learn to find the element’s index in the array.
To check if an element is in an array, we can use Arrays class to convert the array to ArrayList and use the contains() method to check the item’s presence. We can use the indexOf() method to find the index of item in the array.
In the case of an array of custom objects, object equality is checked using the equals() method so the object has implemented the correct and expected equality rules in the overridden equals() method.
String and wrapper classes have already overridden the equals() method so they will work just fine.
String[] fruits = new String[] < "banana", "guava", "apple", "cheeku" >; Arrays.asList(fruits).contains("apple"); // true Arrays.asList(fruits).indexOf("apple"); // 2 Arrays.asList(fruits).contains("lion"); // false Arrays.asList(fruits).indexOf("lion"); // -1
Since Java 8, we can create a stream of items from the array and test if the stream contains the given item or not.
We can use the stream.anyMatch() method that returns whether any element of this stream match the provided Predicate. In the predicate, check the equality to the current element in-stream and the argument element which needs to be found.
Note that Streams also use the equals() method for checking object equality.
String[] fruits = new String[] < "banana", "guava", "apple", "cheeku" >; boolean result = Arrays.asList(fruits) .stream() .anyMatch(x -> x.equalsIgnoreCase("apple")); //true boolean result = Arrays.asList(fruits) .stream() .anyMatch(x -> x.equalsIgnoreCase("lion")); //false
Finally, we can always iterate over the array items using the for-each loop and check whether the item is present in the array.
int[] intArray = new int[]; boolean found = false; int searchedValue = 2; for(int x : intArray) < if(x == searchedValue)< found = true; break; >> System.out.println(found);
Make sure to change the if-condition to a matching equality check if we are using object types.
String[] stringArray = new String[]; boolean found = false; String searchedValue = "B"; for(String x : stringArray) < if(x.equals(searchedValue))< found = true; break; >>