Question: how can I optimize the following:

```
final String[] longStringArray = {"1","2","3".....,"9999999"};
String searchingFor = "9999998"
for(String s : longStringArray)
    {
        if(searchingFor.equals(s))
        {
            //After 9999998 iterations finally found it
            // Do the rest of stuff here (not relevant to the string/array)
        }
    }

```

**NOTE**: The longStringArray is only searched once per runtime & is not sorted & is different every other time I run the program.

Im sure there is a way to improve the worst case performance here, but I cant seem to find it...

P.S. Also would appreciate a solution, where string searchingFor does not exist in the array longStringArray.

Thank you.

Answer: 
```
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.indexOf(array, string);

```

[ArrayUtils documentation](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html)
You can create a second array with the **hash codes** of the string and binary search on that.

You will have to sort the *hash array* and move the elements of the original array accordingly. This way you will end up with extremely fast searching capabilities but it's going to be kept ordered, so inserting new elements takes resources.

The most optimal would be implementing a **binary tree** or a **B-tree**, if you have really so much data and you have to handle inserts it's worth it.