2

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.

3
  • 1
    You 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). Commented Nov 28, 2012 at 19:10
  • ivanovic: loops takes time; in addition, I have to write long code fragments Commented Nov 28, 2012 at 20:06
  • SLaks: There is a problem with hashing that I can't get the index of the element Commented Nov 28, 2012 at 20:06

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.