Close

Java Collections - Collections.binarySearch() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Methods:

These methods search the specified list for the specified object using the binary search algorithm.

public static <T> int binarySearch(List<? extends Comparable<? super T>> list,
                                   T key)
public static <T> int binarySearch(List<? extends T> list,
                                   T key,
                                   Comparator<? super T> c)

Examples


package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BinarySearchExample {

public static void main(String... args) {
List<String> list =
Arrays.asList("one", "two", "three", "four");
Collections.sort(list);
System.out.println("sorted list: " + list);
int index = Collections.binarySearch(list, "three");
System.out.println(index);
}
}

Output

sorted list: [four, one, three, two]
2




package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BinarySearchExample2 {

public static void main(String... args) {
List<Integer> list = Arrays.asList(3, 4, 2, 1, 6, 5);
list.sort(Comparator.reverseOrder());
System.out.println(list);

int index = Collections.binarySearch(list, 4);
System.out.println(index);
}
}

Output

[6, 5, 4, 3, 2, 1]
2




See Also