Java SE API
Collections.binarySearch(List, key, Comparator)
Search with the comparator that defines the existing list order.
Formal Syntax & Structure
java syntaxjava
static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| list | List<? extends T> | List sorted with the given rule. |
| key | T | Value to locate. |
| c | Comparator<? super T> | Same ordering used for sorting; null means natural order. |
Return Value
int
Matching index or encoded insertion position.
Working Example
Example Snippetjava
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> ranks = new ArrayList<>(List.of(5, 20, 10)); Comparator<Integer> order = Comparator.reverseOrder(); ranks.sort(order); System.out.println(ranks); System.out.println(Collections.binarySearch(ranks, 10, order)); System.out.println(Collections.binarySearch(ranks, 15, order)); }}