4 ways to search Java Array to find an element or object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because its one of frequently used operations in Java programming. Array is an index based data structure which is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, array in Java doesn't have any method to check whether an element is inside array or not. Java programming language provides several ways to search any element in Java array. In this Java tutorial we will see 4 examples of searching Array in Java for an element or object.  Every example is different than other and some of them are faster and others are slow but take less memory. These technique also valid for different types of array e.g. primitive and object array. I always suggest to prefer List over Array until you need every bit of performance from your Java application, it not only convenient to work but also more extensible.

4 ways to search array in Java

Here are my 4 ways to search Java Array with examples

1) Searching Array by converting Array to ArrayList in Java
How to search Object in a Java array with exampleArrayList in Java has a convenient method called contains() which returns true if object passed to it are inside ArrayList. by converting an array into ArrayList in Java we can easily use this option for searching any element in Java array.

2) Search Java array by converting Array to HashSet
Just like we can leverage ArrayList's contains method we can also use HashSet contains() method which has O(1) response time for search. So if you need constant search time to find an element in array, consider converting your Array into HashSet in Java. see the code section for complete example of searching elements in Java array using HashSet's contains() method.

3) Searching Java Array using Arrays.binarySearch()
Binary Search is another faster way of searching elements in Java array but it requires array to be sorted while earlier examples of finding elements on Array can be used with both sorted and unsorted array. java.util.Arrays class provides both sort() and binarySearch() for first sorting an array and than performing binary search on it. Arrays.binarySearch() method returns >=0 if it finds elements in Array. see code section for full code example of binarySearch in Java array.

4) Finding element in Java array using foreach loop
This is plain, old, brute force way of searching elements on array in Java or any other programming language like C or C++. You iterate through array comparing each elements to input and returning true once you have matched. this is a completely linear operation and if your array is large and input is at rear end it can take long time to search array. O(n) operations are also not preferred.

One more way of searching an element in array is by using  Apache commons ArrayUtils class. ArrayUtils class provide several overloaded method which accept array and item to be found e.g. int array, long array or Object array and returns true or false if Array contains that element. This requires just one line of code but you need to include Apache commons library in your classpath. See  How to find index of element in Java array for complete code example in Java.

Code Example of Searching Java array to find elements

here is complete code examples of all 4 ways of searching java arrays. you can use any way as per your need but HashSet() is best in terms of speed and consider using that.

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SearchTest {

    public static void main(String args[]) {

        //searching element on unsorted Java array
        //searching java array using ArrayList
        List<Integer> array = Arrays.asList(1, 3, 5, 2, 4);
        if (array.contains(3)) {
            System.out.println("Element found inside Java array using" +
                                 "ArrayList contains() method");

        Set<Integer> arraySet = new HashSet<Integer>(array);

        if (arraySet.contains(3)) {
            System.out.println("Element found on Java array using" +
                                 "HashSet contains method");
        //searching element on sorted Java array
        //unsorted String array
        String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
        //sorting array in java
        //searching on sorted array in java using Arrays binarySearch() method
        if(Arrays.binarySearch(cities, "Paris") >=0 ){
            System.out.println("Element found on sorted String Java" +
                                  "array using binary search");
        //plain old for loop for searching elements in Java array
        String input = "London";
        for(String city: cities){
               System.out.println("Found elements in Java array using for loop");


Element found inside Java array using  ArrayList contains() method
Element found on Java array using HashSet contains method
Element found on sorted String Java array using binary search
Found elements in Java array using for loop

That’s all on How to search an element inside Array in Java. You can use any of the above method to search your Java array for any object. Remember that Collection classes like HashSet and ArrayList use equals() method to determine if two objects are equal or not. So if your testing for custom objects make sure you override equals and hashCode method and follow equals and hashCode contract in Java.

Further Learning
Java Fundamentals: The Java Language by Jim Wilson
Java Fundamentals: Collections
Head First Java

Other Java Collection tutorials and examples from Javarevisited


umesh kukreti said...

I have a question please give me answer with suitable example
Explain how Java addresses the issue of portability and security??

Anonymous said...

wow u r an awesome man.........
excellent coding

Mantoshkumar Singh said...

The following code is not working

int [] numb = {1,3,5,2,4};
List list = new ArrayList(Arrays.asList(numb));
if (list.contains(2)) {
System.out.println("Element found inside Java array using" +
"ArrayList contains() method");

Javin Paul said...

@MantoshKumar, what error you are getting, code looks fine to me.


Search for 6 in (3,4,6,7,8), print the position where it is located and use break to get out of the loop

Javin Paul said...

@Abdul, nice programming exercise, can you also put its solution for benefits of our Java beginners?

Sreekanth Raju said...

i have questoin ... this iz generic
char[] arr = ['0','1','~','n','a','m','e','1','~','h','y','d','&','0','2','~','n','a','m','e','2','~','p','u','n','e'];

It has sets of information like id, name, place seperated by a special char. Each set is again seperated by another special char.
Iterate over the arrays and display the information in the following format. The solution to this problems should be generic.

id : 01
name : name1
place : hyd

id : 02
name : name2
place : pune

Note : Do not use any JAVA API to get the output. Use only loops and conditional statements

Post a Comment