views:

395

answers:

7

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.

+3  A: 

Iterate through the collection and check every element manually.

Esko Luontola
This, really. You could go and make a method for it to simplify things, but your best bet for what I (believe) you want will be to create an array, loop through your passed in collection, and add matching results to your created array, then return it.
Eric
+3  A: 

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?

Winston Chen
I would think it wouldn't be an optimum approach to the problem. Too many iterations, too much processor time.
Jay
But if you don't sort the collection ahead, binary search wouldn't do much help either. If you use certain data structure, like a binary tree, the same question would have some different solutions. Collection is too general. So you may want to choose the right data structure according to your needs.
Winston Chen
Is there any third party API out there which has this kind of feature? Apache Commons? Google Collections?
Jay
I am sorry. I don't know any API for it. However, I think even if you find one, it would probably use loop in their implementation too. So I still recommend you to use loop. If your collection is too big, it takes a long time for a search, then a database engine would be a nice choice, you don't want to store that much data in your memory.
Winston Chen
"Too many iterations, too much processor time." Since there is no order to your elements, you *must* read and check every element, so any approach must iterate through the entire list somehow.
newacct
+5  A: 

You can't binarySearch unless the list is sorted. If it's sorted, then all the matching items are between indexOf and lastIndexOf.

wrang-wrang
+1  A: 

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.

link664
+3  A: 

Try Apache CollectionUtil class method countMatches

techzen
A: 

Check out the Bolts functional programming library. You can do filtering with that.

+1  A: 

Use LambdaJ and you'll have a 'closure like' system for writing your case.

Shimi Bandiel