Sunday, November 4, 2012

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

Other Java Collection tutorials and examples from Javarevisited

2 comments :

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

Post a Comment