How to find if Array contains a value?

Discussing 3 options to find an element in Array in Java

Suraj Mishra
Javarevisited

--

Originally Published in https://asyncq.com/

Introduction

  • Finding value in the collection of value is a very common and often-used operation in software development.
  • I have seen people using all kinds of approaches to solving this problem from naive to optimized.
  • In this article, we will learn the different options to find an element in Array in Java.

Input

  • Our input array contains primitive data of ids. and we need to search if this input array contains id->3.
int[] ids = { 1,2,13,14,15,3,10,11,12,4,5,6,7,8,9 };
int inputId = 3;

Option 1

  • One of the naive approaches is to visit all the elements in the array, one element at a time.
  • Additionally tracking the status of the target element if it exists in the array.
  • As soon we see the element we toggle the status from false to true.
  • Once the loop is finished we return the status flag.
        boolean valExist = false;
for (int id : ids) {
if (inputId == id) {…

--

--

Suraj Mishra
Javarevisited

Staff Software Engineer @PayPal ( All opinions are my own and not of my employer )