Search for a value in Object[] array

1. Overview

In this article, we will see how to search for an object in an Object[] array. For example we will use String[] array.

Embed from Getty Images

2. Content

Linear search algorithm to check if the target element is in array or not. Linear search algorithm searches for given element for the target element until the element is found or all elements have been searched.

2.1 Linear search using equals method

String key = "arya";
String[] arr = { "arya", "jon", "robb", "sansa" };
for (String element : arr) {
    if (key.equals(element)) {
        return true;
    }
}
return false;

2.2. Using Arrays asList method

This method does the job of checking whether value exists or not but there is better way to do it using Java APIs.

boolean contains = Arrays.asList(arr).contains(key);

Arrays class’s asList method accepts var-args as argument and hence array is also accepted but more importantly asList method acts as a bridge between array-based and collection-based APIs. asList method returns a fixed size List backed by specified array. Remember the array is not copied into List. The returned List just references to the array and hence any changes made to array will be visible in returned List too.

2.3. Using Arrays class stream method

Another way to search for a key would be to use Arrays.stream method.

 boolean contains = Arrays.stream(arr).anyMatch(key::equals);

Arrays class has an overloaded method stream which accepts object array and converts it to Stream. Once the array is converted to Stream we can perform Stream related operations on array.

3. Conclusion

In this article, we learned 3 different ways to search for an element in an Object[] array i.e. using plan vanilla for each loop, using Arrays class asList method and using Java 8 stream.

Leave a Reply

Your email address will not be published. Required fields are marked *