Ok. Here is a problem. This is my collection : {2,3,4,2,3,5}
. Let's assume that it is a List
for now. I would like to search this collection for all matches of '2'
. I would like indexes of the same. I know that there are indexOf()
and lastIndexOf()
methods in List
and Arrays.binarySearch()
. However, all of them return one element indicating the position of the searched element. Is there a simple and efficient way to find all matches? Please note that this question is not limited to primitive types.
views:
395answers:
7Iterate through the collection and check every element manually.
If you want all the matches, the most strait-forward way is to loop through it.
Simplicity is the best strategy.
Or you have some particular reason not looping through it?
You can't binarySearch unless the list is sorted. If it's sorted, then all the matching items are between indexOf and lastIndexOf.
Why is it that you want to find the indexes? If possible, consider using something other than a list, like a hash table that allows duplicates or a sorted list so that you reduce your search time. Otherwise the only way you can get all instances of that integer is by manually searching using a for loop.
Check out the Bolts functional programming library. You can do filtering with that.
Use LambdaJ and you'll have a 'closure like' system for writing your case.