Array Search - How to Implement isIn Java
The basic idea behind “isIn” is to inspect an array to see if it contains a given string.
So, in this write-up, we will explore different ways of implementing the “isIn” method in Java.
isIn Java Implementation
Typically, we need to create a static method with two parameters: an array and a given string.
The method should return a boolean value denoting whether the passed string is present in the array.
Using Stream API
Let’s see how we can use the Stream API to achieve our objective:
public static boolean isInUsingStreamApi(String[] array, String value) {
if (array == null || value == null) {
return false;
}
Optional<String> searchedElement = Arrays.stream(array)
.filter(element -> element != null && element.equals(value))
.findFirst();
return searchedElement.isPresent();
}
To keep things simple, we will not repeat the first condition for the remaining implementations.
Using For-each Loop
Next, we will use a for-each loop to iterate through the array. Then, we will check whether each element is equal to the target.
Here’s an example implementation:
public static boolean isInUsingForLoop(String[] array, String value) {
for (String str : array) {
if (str != null && str.equals(value)) {
return true;
}
}
return false;
}
As we can see, we used the equals() method to test if the specified string is in the array.
Using Arrays.binarySearch()
Similarly, we can implement the isIn method using Arrays.binarySearch():
public static boolean isInUsingBinarySearch(String[] array, String value) {
int result = Arrays.binarySearch(array, value);
return result >= 0;
}
Please note that binarySearch() searches for the passed value using the binary search algorithm.
Using Arrays.asList
Alternatively, we can use Arrays.asList() to check whether a string is among the elements:
public static boolean isInUsingArrays(String[] array, String value) {
return Arrays.asList(array)
.contains(value);
}
As shown above, we called contains() which returns true if the searched value exists in the array. Otherwise, false.
Using HashSet
HashSet provides another way to accomplish the same thing:
public static boolean isInUsingHashSet(String[] array, String value) {
Set<String> setSet = new HashSet<>(Arrays.asList(array));
return setSet.contains(value);
}
Conclusion
In this short article, we demonstrated using practical examples how to implement isIn in Java.