Java array search for matching string

how to 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 : longStringArray is checked only once during runtime and is not sorted and changes every time I run the program.

I am sure there is a way to improve the worst case performance here, but I cannot find it ...

PS I would also appreciate a solution in which the string searchFor does not exist in the longStringArray array.

Thank.

+5
source share
4 answers

, , , , , O (N). , , , O (N), - . .

:

+19
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.indexOf(array, string);

ArrayUtils

+6

- .

. , , , .

B-tree, , , .

+1

Arrays.asList(longStringArray).Contains(searchingFor)

0

All Articles