Most Efficient Way to Search Element in Java Array


Using core java we can search an element in an array in many ways. For searching in arrays of primitive or Objects, some methods are common for both and some can be used with in primitive type arrays.

1- For me most efficient method is using Arrays.binarySeach method. It provides an overloaded version for all primitives and with genric type and one comparator to find objects with fields.

This method return index of element, -1 in case of the element not found.

String[] strings = {new String("i"), new String("am"), new String("bad")};
Arrays.binarySearch(strings, "am")

This can search in both primitive and nonprimitive arrays.

2- Since Java 8 we can use Arrays.streams

String[] strings = {new String("i"), new String("am"), new String("bad")};
boolean contains = Arrays.stream(strings).anyMatch("1"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream, or LongStream respectively.

3- Making an immutable list from the array, will only work with a nonprimitive array. Performace will be same but overhead is to wrapping array object inside ArrayList.

String[] strings = {new String("i"), new String("am"), new String("bad")};
if(Arrays.asList(strings).contains("am")){
    System.out.println("Found");
}

Sorting then Searching is not a good option. User Arrays.binarySearch method.

When tested with 10K array size the results were:

Sort & Search : 15
Binary Search : 0
asList.contains : 0
When using a 100K array the results were:

Sort & Search : 156
Binary Search : 0
asList.contains : 32

4- In Java, many people suggest creating one Set or Map then search. In case of when you need to search many elements then this method is good if you need to search one or comparatively fewer elements then use Arrays.binarSearch only, because building Set will be costly in terms of both performance and memory.

HashSet is the best option when you need to search multiple elements in arrays.

String[] strings = {new String("i"), new String("am"), new String("bad")};
Set<String> set = new HashSet<>(Arrays.asList(strings));
set.contains("am");

5- You can also use the Apache commons ArrayUtils class for searching. It has many overloaded indexOf methods, you can also specify a start index.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.