Is there any way to search an ArrayList in Java without using a loop since I have lots of collections to search, and it takes long time to search using loops.
-
1You can either do the looping yourself, or use ArrayList.contains() (which will just use a loop internally). Or (if possible) you can use a Map (as @SLaks has mentioned).jahroy– jahroy2012-11-28 19:10:38 +00:00Commented Nov 28, 2012 at 19:10
-
ivanovic: loops takes time; in addition, I have to write long code fragmentsGhadeer– Ghadeer2012-11-28 20:06:13 +00:00Commented Nov 28, 2012 at 20:06
-
SLaks: There is a problem with hashing that I can't get the index of the elementGhadeer– Ghadeer2012-11-28 20:06:59 +00:00Commented Nov 28, 2012 at 20:06
2 Answers
If you keep your lists sorted, you can search them significantly faster using
Collections.binarySearch(array, key);
in your favorite java.util.Collections class.
Otherwise, you might want to look into TreeSet and HashSet.
But maybe you can improve your overall algorithm? Or build an index?
Comments
If the elements of your array list are not arranged in any particular order, then you have to loop over the list in one way or another.
If the array list does not change, one possibility might be to pre-sort it and then repeatedly use binary search.
Otherwise you'll need to employ a different data structure, such as a Set.