Collections.binarySearch() in Java with Examples - GeeksforGeeks

28 Jun, 2021
java.util.Collections.binarySearch() method is a java.util.Collections class method that returns position of an object in a sorted list. 
// Returns index of key in sorted list sorted in
// ascending order
public static int binarySearch(List slist, T key)

// Returns index of key in sorted list sorted in
// order defined by Comparator c.
public static int binarySearch(List slist, T key, Comparator c)

If key is not present, the it returns "(-(insertion point) - 1)". 
The insertion point is defined as the point at which the key 
would be inserted into the list.
The method throws ClassCastException if elements of list are not comparable using the specified comparator, or the search key is not comparable with the elements.Searching an int key in a list sorted in ascending order:  
Java
// Java program to demonstrate working of Collections.// binarySearch()import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG {    public static void main(String[] args)    {        List<Integer> al = new ArrayList<Integer>();        al.add(1);        al.add(2);        al.add(3);        al.add(10);        al.add(20);         // 10 is present at index 3.        int index = Collections.binarySearch(al, 10);        System.out.println(index);         // 13 is not present. 13 would have been inserted        // at position 4. So the function returns (-4-1)        // which is -5.        index = Collections.binarySearch(al, 13);        System.out.println(index);    }}
Output : 
3
-5
Searching an int key in a list sorted in descending order.  
Java
// Java program to demonstrate working of Collections.// binarySearch() in an array sorted in descending order.import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG {    public static void main(String[] args)    {        List<Integer> al = new ArrayList<Integer>();        al.add(100);        al.add(50);        al.add(30);        al.add(10);        al.add(2);         // The last parameter specifies the comparator        // method used for sorting.        int index = Collections.binarySearch(            al, 50, Collections.reverseOrder());         System.out.println("Found at index " + index);    }}
Output : 
Found at index 1
Searching in a list of user-defined class objects:  
Java
// Java program to demonstrate working of Collections.// binarySearch() in a list of user defined objectsimport java.util.*; class Binarysearch {    public static void main(String[] args)    {        // Create a list        List<Domain> l = new ArrayList<Domain>();        l.add(new Domain(10, "quiz.geeksforgeeks.org"));        l.add(new Domain(20, "practice.geeksforgeeks.org"));        l.add(new Domain(30, "code.geeksforgeeks.org"));        l.add(new Domain(40, "www.geeksforgeeks.org"));         Comparator<Domain> c = new Comparator<Domain>() {            public int compare(Domain u1, Domain u2)            {                return u1.getId().compareTo(u2.getId());            }        };         // Searching a domain with key value 10. To search        // we create an object of domain with key 10.        int index = Collections.binarySearch(            l, new Domain(10, null), c);        System.out.println("Found at index  " + index);         // Searching an item with key 5        index = Collections.binarySearch(            l, new Domain(5, null), c);        System.out.println(index);    }} // A user-defined class to store domains with id and urlclass Domain {    private int id;    private String url;     // Constructor    public Domain(int id, String url)    {        this.id = id;        this.url = url;    }     public Integer getId() { return Integer.valueOf(id); }}
Output : 
0
-1
Arrays.binarysearch() vs Collections.binarySearch() Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList. Important Points:  
If input list is not sorted, the results are undefined.
If there are duplicates, there is no guarantee which one will be found.
This method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
Reference : https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jigneshk5
Prashant__Singh
Binary Search
Java - util package
Java-Collections
Java-Collections-Class
Java-Functions
Java
Java
Binary Search
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Set in Java
Overriding in Java