Introduction
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()
- Using a for-loop
- Collections.binarySearch()
- Java 8 Stream API
- Apache Commons - ArrayUtils
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.
Array of an Integer
type:
Integer[] intArray = new Integer[]{1, 2, 3, 4, 5};
String[] nameArray = new String[]{"John", "Mark", "Joe", "Bill", "Connor"};
List<Integer> intList = new ArrayList<>(Arrays.asList(intArray));
List<String> nameList = new ArrayList<>(Arrays.asList(nameArray));
System.out.println(intList.contains(12));
System.out.println(nameList.contains("John"));
Running this code results in:
false
true
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:
true
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:
false
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.
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.
Let's try this out:
Integer[] intArray = new Integer[]{1, 2, 3, 4, 5};
String[] nameArray = new String[]{"Bill", "Connor", "Joe", "John", "Mark"}; // Array is already sorted lexicographically
List<Integer> intList = new ArrayList<>(Arrays.asList(intArray));
List<String> nameList = new ArrayList<>(Arrays.asList(nameArray));
System.out.println(Collections.binarySearch(intList, 2));
System.out.println(Collections.binarySearch(nameList, "Robin"));
This will output:
1
-6
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));
This will output:
true
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:
false
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"));
This would result in:
true
true
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.