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

Algorithm

  • 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);
      System.out.println(index);
   }
}
class Domain {
   private int id;
   private String url;
   public Domain(int id, String url){
      this.id = id;
      this.url = url;
   }
   public Integer getId() { return Integer.valueOf(id); }
}

Output

Found at index number zone-1
-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();
      ak.add(100);
      ak.add(200);
      ak.add(30);
      ak.add(10);
      ak.add(20);

      int index = Collections.binarySearch(ak, 100);
      System.out.println(index);
      index = Collections.binarySearch(ak, 130);
      System.out.println(index);
	}
}

Output

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

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>();
      a0710.add(1000);
      a0710.add(500);
      a0710.add(300);
      a0710.add(10);
      a0710.add(2);
      int index = Collections.binarySearch(
      	a0710, 50, Collections.reverseOrder());

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

Output

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.in);
      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) + ".");
           break;
         }
         else{
             last = middle - 1;
         }
         middle = (first + last)/2;
      }
      if ( first > last )
         System.out.println(item + " is not found.\n");
   }
}

Output

Enter number of elements:
7
Enter 7 integers
10
12
56
42
48
99
100
Enter the search value:
50
50 is not found.

Conclusion

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

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements