Java Collections binarySearch() Method
Example
Sort a list, then find the position of "Ford":
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars);
System.out.println(cars);
System.out.println(Collections.binarySearch(cars, "Ford"));
}
}
Definition and Usage
The binarySearch() method searches a list for an item and returns its index (position). It uses binary search (a fast search that splits the list in half again and again), so the list must be sorted first.
If the item is not found, the method returns a negative number.
Tip: Use Collections.sort() before you search. If the list is not sorted, the result can be wrong.
Syntax
One of the following:
public static int binarySearch(List<T> list, T key)
public static int binarySearch(List<T> list, T key, Comparator c)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The sorted list to search in. |
| key | Required. The item to search for. |
| c | Optional. The Comparator that was used to sort the list. |
Technical Details
| Returns: | The index of the item, if it is found. Otherwise a negative number. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods