The Wayback Machine - https://web.archive.org/web/20241001035614/https://www.geeksforgeeks.org/collections-binarysearch-java-examples/
Open In App

Collections.binarySearch() in Java with Examples

Last Updated : 30 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 objects
import java.util.*;
 
class Binarysearch {
    public static void main(String[] args)
    {
        // Create a list
        List<Domain> l = new ArrayList<Domain>();
        l.add(new Domain(10, "www.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 url
class 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

Found at index  0
-1

Complexity Analysis:

Time Complexity:
The time complexity of the binarySearch() method in the Collections class is O(log n), where n is the size of the list.

Auxiliary Space:
The space complexity of the binarySearch() method in the Collections class is O(1), as it does not require any additional data structures to be created.

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)

 



Previous Article
Next Article

Similar Reads

Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
Arrays.binarySearch()| Set 1 Covers how to find an element in a sorted array in Java. This set will cover "How to Search a key in an array within a given range including only start index". Syntax : public static int binarySearch(data_type[] arr, int fromIndex, int toIndex, data_type key) Parameters : arr – the array to be searched fromIndex – the i
5 min read
Arrays.binarySearch() in Java with examples | Set 1
Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted as by the Arrays.sort() method prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no g
5 min read
Difference between Traditional Collections and Concurrent Collections in java
We all know about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like: Most of the Classes which are present in Traditional Collections (i.e ArrayList, L
3 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
Java.util.Collections.disjoint() Method in java with Examples
java.util.Collections.disjoint() method is present in java.util.Collections class. It is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. Syntax: public static boolean disjoint(Collection<?> c1, Collection<?> c2) Parameters : c1 - a colle
3 min read
Collections checkedMap() method in Java with Examples
The checkedMap() method of Collections class been present inside java.util package is used to return a dynamically typesafe view of the specified map. The returned map will be serializable if the specified map is serializable. Since null is considered to be a value of any reference type, the returned map permits the insertion of null keys or values
3 min read
Collections singletonMap() method in Java with Examples
The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable. Syntax: public static Map singletonMap(K key, V value) Parameters: This method takes the following parameters as a argument: key - the sole key to be stored in the retu
2 min read
Collections min() method in Java with Examples
min(Collection<? extends T> coll) The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (tha
4 min read
Collections max() method in Java with Examples
max(Collection<? extends T> coll) The max() method of java.util.Collections class is used to return the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (tha
5 min read
Collections addAll() method in Java with Examples
The addAll() method of java.util.Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under
3 min read
Collections asLifoQueue() method in Java with Examples
The asLifoQueue() method of java.util.Collections class is used to return a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.Each method invocation on the queue returned by thi
2 min read
Collections checkedCollection() method in Java with Examples
The checkedCollection() method of java.util.Collections class is used to return a dynamically typesafe view of the specified collection. The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these
3 min read
Collections checkedList() method in Java with Examples
The checkedList() method of Collections class is present inside java.util package is used to return a dynamically typesafe view of the specified list. The key thing to note here is that the returned list will be serializable if the specified list is serializable. Since null is considered to be a value of any reference type, the returned list permit
3 min read
Collections checkedSet() method in Java with Examples
The checkedSet() method of java.util.Collections class is used to return a dynamically typesafe view of the specified set.The returned set will be serializable if the specified set is serializable.Since null is considered to be a value of any reference type, the returned set permits insertion of null elements whenever the backing set does.Syntax: p
2 min read
Collections checkedSortedMap() method in Java with Examples
The checkedSortedMap() method of java.util.Collections class is used to return a dynamically typesafe view of the specified sorted map.The returned map will be serializable if the specified map is serializable.Since null is considered to be a value of any reference type, the returned map permits insertion of null keys or values whenever the backing
2 min read
Collections checkedSortedSet() method in Java with Examples
The checkedSortedSet() method of java.util.Collections class is used to return a dynamically typesafe view of the specified sorted set.The returned sorted set will be serializable if the specified sorted set is serializable.Since null is considered to be a value of any reference type, the returned sorted set permits insertion of null elements whene
2 min read
Collections enumeration() method in Java with Examples
The enumeration() method of java.util.Collections class is used to return an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.Syntax: public static Enumeration enumeration(Collection c) Parameters: This method takes the collection c as a parameter for which an enumeratio
2 min read
Collections copy() method in Java with Examples
The copy() method of java.util.Collections class is used to copy all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in
3 min read
Collections fill() method in Java with Examples
The fill() method of java.util.Collections class is used to replace all of the elements of the specified list with the specified element. This method runs in linear time. Syntax: public static void fill(List list, T obj) Parameters: This method takes following argument as parameter list - the list to be filled with the specified element. obj - The
2 min read
Collections indexOfSubList() method in Java with Examples
The indexOfSubList() method of java.util.Collections class is used to return the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. More formally, returns the lowest index i such that source.subList(i, i+target.size()).equals(target), or -1 if there is no su
3 min read
Collections list() method in Java with Examples
The list() method of java.util.Collections class is used to return an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections. Syntax: public static ArrayList li
2 min read
Collections newSetFromMap() method in Java with Examples
The newSetFromMap() method of java.util.Collections class is used to return a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to any Map implementation. There is no need to use t
2 min read
Collections replaceAll() Method in Java with Examples
The replaceAll() method of java.util.Collections class is used to replace all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in the list such that oldVal == null ? e==null : oldVal.equals(e) Note: This method has no effect on the size of the list. Parameters: This method takes the follo
3 min read
Collections swap() method in Java with Examples
The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged. Syntax: public static void swap(List list, int i, int j) Parameters: This method takes the following argument as a Parameter list - The
2 min read
Collections synchronizedCollection() method in Java with Examples
The synchronizedCollection() method of java.util.Collections class is used to return a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.Syntax: public static <T> Collection<T
2 min read
Collections synchronizedList() method in Java with Examples
The synchronizedList() method of java.util.Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. Syntax: public static <T> List<T> synchronizedList(List<T>
2 min read
Collections synchronizedMap() method in Java with Examples
The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map. Syntax: public static <K, V> Map<K, V> synchronizedMap(Map<K, V
2 min read
Collections synchronizedSet() method in Java with Examples
The synchronizedSet() method of java.util.Collections class is used to return a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. Syntax: public static <T> Set<T> synchronizedSet(Set<T> s) Para
2 min read
Collections synchronizedSortedMap() method in Java with Examples
The synchronizedSortedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) sorted map backed by the specified sorted map. In order to guarantee serial access, it is critical that all access to the backing sorted map is accomplished through the returned sorted map (or its views). Syntax: public static <K, V
2 min read
Collections synchronizedSortedSet() method in Java with Examples
The synchronizedSortedSet() method of java.util.Collections class is used to return a synchronized (thread-safe) sorted set backed by the specified sorted set. In order to guarantee serial access, it is critical that all access to the backing sorted set is accomplished through the returned sorted set (or its views). Syntax: public static <T>
2 min read