How do i find all objects which match a search cirteria in a binary search?

I am using a binary search (collections.binarySearch) to search through a collection for a certain object paratmeter string, now if it exists, it will only find 1 result, but what if there are more objects with that parameter string, how can i print them all?
Who is Participating?
javaexpertoConnect With a Mentor Commented:
What you want to do is an inneficient way to achieve your goal. Use the code I wrote above. If you really wanto to use binary search I give you the code.
al is your List and "c" is the String that you are looking for. Please note that if your String is in the beggining of the List or at the end, it will throw an index Exception. If it is the case you would never should use binarySearch.
Good luck

    	int index = Collections.binarySearch(al, "c");
    	int cont = index;
    	for(int i = 0; i < al.size(); i++) {
    		if(al.get(index - i) == "c") {
    		} else {
    	for(int i = 0; i < al.size(); i++) {
    		if(al.get(cont + 1) == "c") {
    			System.out.print(al.get(cont + 1));

Open in new window

IF you know how many objects are int your list, you can call binarySearch method and then print the values using the index + 1... index + number of objects.

If you don't know get the index of your first and last object, for example:


      int s = al.indexOf("b"); //here al is an ArrayList
      int f = al.lastIndexOf("b");
        for(int i = s; i <= f; i++) {

Open in new window

try subList()

Collections.binarySearch(list.subList(startIndex, endIndex), ....

area96Author Commented:
Thanks for the help guys, It hasnt entirely solved my problem though, as a binary search could drop you anywhere within the block of the array which matches the String that is being searched for, I would need to traverse back through the array until the string does not equal what im lookign for, then work forwards printing out every result..

Im so close I just need come help with the coding of this..

Either that or i havent fully understood your advice above.
Any more help would be greatly appreciated!  Thanks!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.