I have an arraylist with several items. Let\'s say they are: \"DARK BROWN\", \"BLUE\", \"GREEN\",....
Is there any way to look for if there\'s the string \"DARK\" in
Keep the strings in a sorted(!) array and use binarysearch
to find the insertion point of your prefix. The matches will be at that point, if at all.
Performance if this is O(log n) instead of O(n), you should find it to be much faster, in particular for large data sets.
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class ContainsPrefix {
public static String findWithPrefix(String[] data, String prefix) {
int n = Arrays.binarySearch(data, prefix);
if (n < 0) n = -1 - n;
// Loop here if you want to find all matches ...
if (!data[n].startsWith(prefix)) return null;
return data[n];
}
@Test
public void shouldFindStringWithPrefix() {
String[] data = { //
"David's cat is in his bedroom", //
"I like the moon", //
"I want to travel to Mars", //
"My ball is red", //
"They always forget about Antarctida", //
"..." //
};
Arrays.sort(data);
String found = findWithPrefix(data, "I want to");
assertEquals("I want to travel to Mars", found);
}
}