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 some of my items? I know that contains does this but it only does if the string is exactly. My idea is to look for a text that starts as one of my items but it hasn't all the last characters.
I have thougth in do a loop like:
for(int i=0;i<arraylist.size;i++){
String s = arraylist.get(i);
if (s.startsWith(mytext)){
do something
}
}
but it seems to be a very slow method because the arraylist can contain a lot of elements. Any better ideas?
EDIT
Just to be sure you understand my point. I want to know if an item of my arraylist contains an element that starts with some text and to get the complete text of that element. ArrayList.contains is a boolean. If I need to retrieve information I will have to use IndexOf or so but this function gives me null if I put "brown"
EDIT 2
This is for you auselen:
Arraylist (5000 elements or so):
- "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"
- ...
I want to know if there's an element that starts with "I want to" and then retrieve the rest of the element.
Or you can use completly different approach. and wrap ArrayList and check upon list.add() for a match. And store it in some var for quick access. But if you have multiple values to search, then this approach is not good at all :).
Either do it like you have done it, or it gets much more complex. There is a search structure called "trie" , but this is complex.
You could gain a bit by having an array of a- z pointing to the start position in your sorted ArrayList of the first letter. Then you only have to search within the words that start with the same letter.
Like, a million?
Code
Here is an example of a function you could use with getting each item. The speed of this is not really an increase. Due to this being an arraylist there is not really a good way to do this. There are better data structures for searching for parts of a string.
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.