Reputation: 2454
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.
Upvotes: 0
Views: 5152
Reputation: 5747
Use LambdaJ and you'll have a 'closure like' system for writing your case.
Upvotes: 1
Reputation:
Check out the Bolts functional programming library. You can do filtering with that.
Upvotes: 0
Reputation: 7012
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.
Upvotes: 1
Reputation: 9301
You can't binarySearch unless the list is sorted. If it's sorted, then all the matching items are between indexOf and lastIndexOf.
Upvotes: 5
Reputation: 6879
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?
Upvotes: 3
Reputation: 73645
Iterate through the collection and check every element manually.
Upvotes: 3