Search for a value in an array

1. Overview

In this article, we will see how to search for a value in an array. For example we will use int[] array.

Embed from Getty Images

2. Content

Let say for example we have int[] arr = { 4, 67, 3, 4, 2 }. The method we will use to search for given element in an array is linear search algorithm. 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

Linear search algo is as below:

int[] arr = { 4, 67, 3, 4, 2 };

for (int element : arr) {
    // check if target element i.e. key and element are same
    if (key == element) { 
        return true; // if they are same return true
    }
}
return false; // all elements traversed and target element not found

This method does the job of searching an element and works well. But there is a better way of searching an element in Java 8.

2.2. Using primitive stream

boolean contains = IntStream.of(arr)
                            .anyMatch(value -> key == value);

As Java 8 provides declarative way to access array using IntStream it becomes easy for us to write code as streams handle the iteration we just need to provide behavior to the methods i.e. Lambda expression.

As of long[] and double[] we can use LongStream and DoubleStream respectively to search for a given key in an array.

3. Conclusion

In this article, we explored 2 different ways to search for an element in an array i.e. using plan vanilla for each loop and using Java 8 primitive stream.

Join the Newsletter

Download Complete Guide to Comparators in
1. Java 8
2. Map.Entry Interface
3. Spring
4. Google Guava
5. Apache Collections
with more than 60 examples. One book to know and learn it all.

    We respect your privacy. Unsubscribe at any time.

    Leave a Reply

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