how to get highest and lowest index position in Collections.binarysearch() through key value
int curIndex = Collections.binarysearch(myList,"String");
int highIndex = ?
You're already making an incorrect assumption: that the value returned will be the lowest index. From the documentation:
If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.
Basically, once you've found one match, you just need to walk down the list until you find a non-match to get the lowest index, and walk up the list until you find a non-match to get the highest index.
int found = Collections.binarySearch(myList, "String");
int lowIndex = found;
while (lowIndex > 0 && myList.get(lowIndex - 1).equals("String")) {
lowIndex--;
}
int highIndex = found;
while (highIndex + 1 < myList.size()
&& myList.get(highIndex + 1).equals("String")) {
highIndex++;
}
(You could rewrite those while
loops as for
loops with an empty body if you wanted to, but I find this more readable.)
See more on this question at Stackoverflow