- Arrays are use to hold large amount of values or Object instances.
- But a common problem is checking if a given array contains a specific value. There are several ways of doing this, some are efficient and some are not.
- Below are some examples on how to test if a Java array contains a certain value.
Check Array Contains Using For Loop
- The easiest method for searching if an array contain a specific value is by coding it using for loop.
- Here is an example:
- The for loop is used to go through each item of the array one by one and compare. True is returned if one matches the item, otherwise false is returned.
- The output of the code will be:
- true
- False
- Because 13 is in the given array, while 25 is not. Note that this is not a very efficient solution since the code may potentially compare all items in the array.
Check Array Contains Using Arrays.binarySearch
- The Arrays.binarySearch can also be used to check if a given value exists in an array.
- The benefit of binary search becomes more apparent when the size of the array becomes larger.
Below is an example of how to check is an array contains a value using binary search:
- The binary search gives the index of the item in the array. If the index is negative, it means the item is not found. Otherwise, it means it exist in the array.
- Binary search have one big assumption. The array is ASSUMED TO BE SORTED for it to return a correct result.
- Hence the code “Arrays.sort(myArray);” is important prior to calling binary search. If we ommit this, the result will be unpredictable.
For example:
[ad type=”banner”]The call to sort was taken out and the output will not be correct.
The code above will display:
- False
- False
- Which is not correct.
Check Array Contains Using List
- A List has a built-in method to check if it contains a specific value.
- We can use this to test if an Java array contains a value.
- First , We need to convert the array to List, and then invoke the contains method of the List.
Here is an example code:
Check Array Contains Using Set
- Similar to List, a Set also have the method contains to check if it has a certain value.
- We can also use this for checking if an array contains a certain value.
For example:
- A Set is conceptually more efficient than List because it does not contain duplicate values.
It should use fewer comparison than a List. - Check Array Contains Using Stream of Java 8
- If you are using Java 8 or higher, using stream is another option for finding if an item exist in the array.
Here is a sample code:
[ad type=”banner”]