Wednesday, August 11, 2021

4 Ways to Search Java Array to Find an Element or Object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because it's one of the frequently used operations in Java programming. The array is an index-based data structure that is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, the array in Java doesn't have any method to check whether an element is inside an array or not. Java programming language provides several ways to search any element in the 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 others and some of them are faster and others are slow but take less memory.

These techniques are also valid for different types of arrays e.g. primitive and object arrays. I always suggest preferring List over Array until you need every bit of performance from your Java application, it is not only convenient to work but also more extensible.



4 ways to search array in Java - Examples 

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 the 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 the foreach loop

This is a 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 element 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 the rear end it can take a long time to search the array. O(n) operations are also not preferred.

One more way of searching an element in the array is by using the 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
        Arrays.sort(cities);
     
        //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){
            if(city.equals(input)){
               System.out.println("Found elements in Java array using for loop");
            }
        }

    }
}

Output
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 an Array in Java. You can use any of the above methods 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 the equals and hashCode method and follow equals and hashCode contract in Java.


Other Java Collection tutorials and examples from Javarevisited

12 comments:

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

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

    ReplyDelete
  3. 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");

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

    ReplyDelete
  5. 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

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

    ReplyDelete
  7. 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

    ReplyDelete
  8. Hi Sreekanth Raju,
    I have added the code snippet below
    char[] arr = {'0','1','~','n','a','m','e','1','~','h','y','d','&','0','2','~','n','a','m','e','2','~','p','u','n','e'};
    String a=String.valueOf(arr);
    String array1[]=a.split("&");

    for (int i=0;i<array1.length;i++) {
    //System.out.println(array1[i]);
    String array2[]=array1[i].split("~");
    for (int j=0;j<array2.length;j++) {
    System.out.println(array2[j]);
    }
    }

    ReplyDelete
  9. char[] arr = {'0','1','~','n','a','m','e','1','~','h','y','d','&','0','2','~','n','a','m','e','2','~','p','u','n','e'};
    String a=String.valueOf(arr);
    String array1[]=a.split("&");

    for (int i=0;i<array1.length;i++) {
    //System.out.println(array1[i]);
    String array2[]=array1[i].split("~");
    for (int j=0;j<array2.length;j++) {
    System.out.println(array2[j]);
    }
    }

    ReplyDelete
  10. char[] arr = {'0','1','~','n','a','m','e','1','~','h','y','d','&','0','2','~','n','a','m','e','2','~','p','u','n','e'};
    String a=String.valueOf(arr);
    String array1[]=a.split("&");

    for (int i=0;i<array1.length;i++) {
    //System.out.println(array1[i]);
    String array2[]=array1[i].split("~");
    for (int j=0;j<array2.length;j++) {
    System.out.println(array2[j]);
    }
    }

    ReplyDelete
  11. Its a very effective way to search array element in java its easy to understand thanks sharing this post keep updating like this post....

    ReplyDelete
  12. Thanks Vikram, happy that you find this tutorial useful.

    ReplyDelete