Jay
Jay

Reputation: 2454

Find all matches in a Java Collection

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

Answers (7)

techzen
techzen

Reputation: 2955

Try Apache CollectionUtil class method countMatches

Upvotes: 3

Shimi Bandiel
Shimi Bandiel

Reputation: 5747

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

Upvotes: 1

Matthias Fraass
Matthias Fraass

Reputation:

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

Upvotes: 0

dnatoli
dnatoli

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

Jonathan Graehl
Jonathan Graehl

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

Winston Chen
Winston Chen

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

Esko Luontola
Esko Luontola

Reputation: 73645

Iterate through the collection and check every element manually.

Upvotes: 3

Related Questions