Java Program to Search User Defined Object From a List By using Binary Search Comparator

Java comparator interface used to sort Java objects. A comparator class in Java compares the different objects (Obj 01, Obj 02) by invoking the "java. util. comparator". In this method the objects can be compared on the basis of the return value. It can be positive, equal or negative in comparison.

The process provides user multiple sorting sequences. There are lots of method by which we can perform the comparison between two methods.

  • public int compare class (obj 1, obj 2) - Perform comparison between two objects.

  • public Boolean equals (obj) - Compare current object with specified object.

Java collection class - provides the static method of sorting elements from a collection of data. Here collection elements are used for the TreeMap.

Let’s discuss how to build a Java code to search user defined object from a list by using binary search using comparator.

Binary search parameters and its components

  • Parameters

    • is a particular array

    • fromindex - first element to be searched

    • toindex - last element to be searched

    • key - value to be searched

    • comparator

  • Return

    • Returns the index of a search key present in the specified range.

  • Exceptions

    • ClassCast

    • IllegalArgument

    • ArrayIndexOutOfBounds


  • Step 1 − Start.

  • Step 2 − Mid element collection calculation.

  • Step 3 − Compare the key with a mid-element.

  • Step 4 − If, the value of key and mid element both are same; then Return the result.

  • Step 5 − Else, the value of key is greater than mid element, follow right half collection

  • Step 6 − Or; if the value of the key is less than mid element then follow upper

Binary search using comparator - Syntax 

public static int binarySearch(primitive() p,Primitive key)
public static int binarySearch(Object() o,Object key)

public static int binarySearch(Object() o,Object key,Comparator c)
Java Collections binarySearch(List<? extends Comparable1<? super R>> list, R key)and;
Java Collections binarySearch(List<? extends R> list, R key, Comparator<? super R> c)

There are two well know syntax for to search user defined object from a list by using binary search using comparator. For the first case, the list needs to be sorted in an ascending order with the particular method calling process where the result is undefined.

On the other hand; to search a specified object it is important to call the method.

Approach to follow

  • Approach 1 − Searching user defined object from a list by comparator using binary search

Searching a user defined object from a list using comparator

In these examples, we have used collection, binarySearch() and comparator class operation to sort some user defined data by comparator using binary Search operation

Example 1: Finding a data from a list using Collections, binarySearch()

import java.util.*;

public class Binarysearch {
   public static void main(String[] args){
      List<Domain> l1 = new ArrayList<Domain>();
      l1.add(new Domain(100, "India"));
      l1.add(new Domain(200, "Bangladesh"));
      l1.add(new Domain(300, "Dhaka"));
      l1.add(new Domain(400, "Kolkata"));

      Comparator<Domain> c = new Comparator<Domain>() {
      	 public int compare(Domain u1, Domain u2) {
            return u1.getId().compareTo(u2.getId());
      int index = Collections.binarySearch(	l1, new Domain(10, null), c);
      System.out.println("Found at index number zone" + index);
      index = Collections.binarySearch(l1, new Domain(6, null), c);
class Domain {
   private int id;
   private String url;
   public Domain(int id, String url){ = id;
      this.url = url;
   public Integer getId() { return Integer.valueOf(id); }


Found at index number zone-1

Example 2: Sorting a list in ascending order

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ascendingsearch {
	public static void main(String[] args){
      List<Integer> ak = new ArrayList();

      int index = Collections.binarySearch(ak, 100);
      index = Collections.binarySearch(ak, 130);


Note: uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Example 3: Sorting a list in descending order and find the index number

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class binsearchdecend {
	public static void main(String[] args){
      List<Integer> a0710 = new ArrayList<Integer>();
      int index = Collections.binarySearch(
      	a0710, 50, Collections.reverseOrder());

      System.out.println("Found at index number present " + index);


Found at index number present -4

Example 4: Find the number of elements and values

import java.util.Scanner;
public class BinarySearchExample{
   public static void main(String args[]){
      int counter, num, item, array[], first, last, middle;
      Scanner input = new Scanner(;
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      for (counter = 0; counter < num; counter++)
          array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last ){
         if ( array[middle] < item )
           first = middle + 1;
         else if ( array[middle] == item ){
           System.out.println(item + " found at location " + (middle + 1) + ".");
             last = middle - 1;
         middle = (first + last)/2;
      if ( first > last )
         System.out.println(item + " is not found.\n");


Enter number of elements:
Enter 7 integers
Enter the search value:
50 is not found.


In this article, we have learnt about the Comparable interface in Java using some example codes and algorithms. Here we have declared some user-defined classes and the comparator interface. They have some specific use which allows to deal with the particular data in a Java environment.

Updated on: 11-Apr-2023


Kickstart Your Career

Get certified by completing the course

Get Started