- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Perform Binary Search on ArrayList with Java Collections
In order to perform Binary Search on ArrayList with Java Collections, we use the Collections.binarySearch() method.
Declaration −The java.util.Collections.binarySearch() method is declared as follows −
public static int binarySearch(List list, T key)
The above method returns the position of the key in the list sorted in ascending order. If we use a Comparator c to sort the list, the binarySearch() method will be declared as follows −
public static int binarySearch(List list, T key, Comparator c)
If key is not present, the it returns ((insertion point) + 1) *(-1).
Let us see a program to perform binarySearch() on ArrayList −
Example
import java.util.*; public class Example { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(7); int pos = Collections.binarySearch(list, 1); // 1 is present at 0th index System.out.println(pos); pos = Collections.binarySearch(list, 5); /* since 5 is not present and it would be inserted at index 2 the method returns (-1)*() */ System.out.println(pos); } }
Output
0 -3
- Related Articles
- How to perform binary search on an array in java?
- Get Enumeration over ArrayList with Java Collections
- Shuffle elements of ArrayList with Java Collections
- Swap elements of ArrayList with Java collections
- Perform Binary Search in Java using Collections.binarySearch
- Replace All Elements Of ArrayList with with Java Collections
- Find maximum element of ArrayList with Java Collections
- Find minimum element of ArrayList with Java Collections
- Copy Elements of One ArrayList to Another ArrayList with Java Collections Class
- Reverse order of all elements of ArrayList with Java Collections
- Sort ArrayList in Descending order using Comparator with Java Collections
- Replace all occurrences of specified element of ArrayList with Java Collections
- C++ Program to Perform Left Rotation on a Binary Search Tree
- C++ Program to Perform Right Rotation on a Binary Search Tree
- C++ Program to Perform Uniform Binary Search

Advertisements