1. Overview
In this article, we will see how to search for a value in an array. For example we will use int[] array.
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.