Searching, Filing, and Copying Collection

Let's discuss some operations available in the Collections class.

Searching an element in a Collection

The binarySearch(List list, T key) method searches the specified list for the specified object using the binary search algorithm. The elements added in the List must implement the Comparable interface, and the list must be sorted into ascending order before making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

If the elements added to our List do not implement the Comparable interface, then we can use another overloaded version of binarySearch(List list, T key, Comparator comp), which takes a Comparator for the input as well. The list must be sorted into ascending order according to the specified comparator.

If the element is not present in the list, then this method returns a position where the element can be inserted.

Get hands-on with 1400+ tech skills courses.