Ghadeer
Ghadeer

Reputation: 638

Search an arraylist without loop in java

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.

Upvotes: 2

Views: 3333

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

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?

Upvotes: 5

NPE
NPE

Reputation: 500327

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.

Upvotes: 2

Related Questions