Table of Contents
Binary search parameters and their components
algorithm
Binary search using comparator - syntax
Following method
Search for user-defined objects from a list using a comparator
Example 1: Use Collections, binarySearch() to find data from a list
Output
Example 2: Sort the list in ascending order
Example 3: Sort the list in descending order and find the index number
Example 4: Find the number of elements and values
in conclusion
Home Java javaTutorial Java program to search user defined object from list by using binary search comparator

Java program to search user defined object from list by using binary search comparator

Aug 28, 2023 pm 04:05 PM
java program Comparators binary search

Java program to search user defined object from list by using binary search comparator

Java comparator interface for sorting Java objects. Comparator classes in Java compare different objects (Obj 01, Obj 02) by calling "java.util.comparator". In this method, objects can be compared based on the return value. The comparison can be positive, equal, or negative.

This process provides the user with multiple sorting sequences. There are many ways to compare the two methods.

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

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

Java Collection Class - Provides static methods for sorting elements in a data collection. This collection element is used in TreeMap.

Let us discuss how to build a Java code using comparators to search for a user-defined object from a list via binary search.

Binary search parameters and their components

  • parameter

    • is a specific array

    • fromindex - the first element to search for

    • toindex - the last element to search for key - the value to search for Key-value pairs to be searched

    • Comparators

  • return

    • Returns the index of the search key that exists within the specified range.

  • exception

    • ClassCast

    • Illegal parameter

    • ArrayIndexOutOfBounds

algorithm

  • Step one - start.

  • Step 2 - Intermediate element set calculation.

  • Step 3 - Compare the keyword to the middle element.

  • Step 4 - If the values ​​of key and mid elements are the same; then return the result.

  • Step 5 - Otherwise, the value of the key is greater than the middle element, then follow the right half of the collection

  • Step 6 - Or; if the value of key is less than the 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)
Copy after login

There are two well-known syntaxes to search for user-defined objects from lists via binary search using comparators. For the first case, the list needs to be sorted in ascending order and the procedure is called using a specific method, where the result is undefined.

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

Following method

  • Method 1 to search for a user-defined object from a list by using a binary searcher and comparator

Search for user-defined objects from a list using a comparator

In these examples, we use collections, binarySearch() and comparator class operations to sort some user-defined data using the binary search operation through the comparator

Example 1: Use Collections, binarySearch() to find data from a list

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); }
}
Copy after login

Output

Found at index number zone-1
-1
Copy after login

Example 2: Sort the 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<integer>();
      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);
	}
}
</integer>
Copy after login

Output

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

Example 3: Sort the 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);
	}
}
Copy after login

Output

Found at index number present -4
Copy after login

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");
   }
}
Copy after login

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.
Copy after login

in conclusion

In this article, we learned about the Comparable interface in Java through some sample codes and algorithms. Here we declare some user-defined classes and comparator interfaces. They serve some specific purposes and allow specific data to be processed in a Java environment.

The above is the detailed content of Java program to search user defined object from list by using binary search comparator. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java program opens command prompt and inserts command Java program opens command prompt and inserts command Aug 19, 2023 pm 12:29 PM

ThisarticleusesvariousapproachesforselectingthecommandsinsertedintheopenedcommandwindowthroughtheJavacode.Thecommandwindowisopenedbyusing‘cmd’.Here,themethodsofdoingthesamearespecifiedusingJavacode.TheCommandwindowisfirstopenedusingtheJavaprogram.Iti

Java program used to check if TPP students are eligible for interviews Java program used to check if TPP students are eligible for interviews Sep 06, 2023 pm 10:33 PM

Please consider the table below to know the eligibility criteria of different companies - The Chinese translation of CGPA is: GPA greater than or equal to 8 Eligible companies Google, Microsoft, Amazon, Dell, Intel, Wipro greater than or equal to 7 Tutorial points, accenture, Infosys , Emicon, Rellins greater than or equal to 6rtCamp, Cybertech, Skybags, Killer, Raymond greater than or equal to 5Patronics, Shoes, NoBrokers Let us enter the java program to check the eligibility of tpp students for interview. Method 1: Using ifelseif condition Normally when we have to check multiple conditions we use

Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Aug 20, 2023 pm 10:49 PM

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

Java program to get the size of a given file in bytes, kilobytes and megabytes Java program to get the size of a given file in bytes, kilobytes and megabytes Sep 06, 2023 am 10:13 AM

The size of a file is the amount of storage space that a specific file takes up on a specific storage device, such as a hard drive. The size of a file is measured in bytes. In this section, we will discuss how to implement a java program to get the size of a given file in bytes, kilobytes and megabytes. A byte is the smallest unit of digital information. One byte equals eight bits. One kilobyte (KB) = 1,024 bytes, one megabyte (MB) = 1,024KB, one gigabyte (GB) = 1,024MB and one terabyte (TB) = 1,024GB. The size of a file usually depends on the type of file and the amount of data it contains. Taking a text document as an example, the file size may be only a few kilobytes, while a high-resolution image or video file may be

Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Sep 03, 2023 am 11:37 AM

The Java language is one of the most commonly used object-oriented programming languages ​​in the world today. The concept of classes is one of the most important features of object-oriented languages. A class is like a blueprint for an object. For example, when we want to build a house, we first create a blueprint of the house, in other words, we create a plan that shows how we are going to build the house. According to this plan we can build many houses. Likewise, using classes, we can create many objects. Classes are blueprints for creating many objects, where objects are real-world entities like cars, bikes, pens, etc. A class has the characteristics of all objects, and the objects have the values ​​of these characteristics. In this article, we will write a Java program to find the perimeter and faces of a rectangle using the concept of classes

JAVA program to convert Roman numerals to integer numbers JAVA program to convert Roman numerals to integer numbers Aug 25, 2023 am 11:41 AM

Roman Numerals - Based on the ancient Roman system that uses symbols to represent numbers. These numbers are called Roman numerals. The symbols are I, V, X, L, C, D and M, which represent 1, 5, 10, 50, 100, 500 and 1,000 respectively. Integers - An integer is an integer consisting of positive, negative and zero values. Fractions are not whole numbers. Here we set the symbol value based on the integer value. Whenever a Roman numeral is given as input, we divide it into units and then calculate the appropriate Roman numeral. I-1II–2III–3IV–4V–5VI–6…X–10XI–11..XV-15 In this article, we will learn how to convert Roman numerals to integers in Java. Show you some examples - Example 1InputR

Java program to rotate image Java program to rotate image Sep 01, 2023 pm 04:25 PM

An image file can be rotated clockwise or counterclockwise. To rotate an image, you need to download a random image file and save it in any folder on your system. Also, a .pdf file is required and after opening the downloaded image file, some angle can be rotated in that particular .pdf file. For a 90 degree rotation, the anchor points of the new image can help us perform the rotation using the translation transform in Java. The anchor point is the center of any particular image. AlgorithmtoRotateanImagebyUsingJavaThe"AffineTransformOp"classisthesimplestwaytorotatea

Java program to create pyramids and patterns Java program to create pyramids and patterns Sep 05, 2023 pm 03:05 PM

If anyone wants to get a solid foundation in Java programming language. Then, it is necessary to understand how the loop works. Furthermore, solving Pyramid Pattern problems is the best way to enhance your knowledge of Java basics as it includes extensive use of for and while loops. This article aims to provide some Java programs to print pyramid patterns with the help of different types of loops available in Java. Java Program to Create Pyramid Pattern We will print the following pyramid patterns through Java program - Inverted Star Pyramid Star Pyramid Number Pyramid Let's discuss one by one. Mode 1: The inverted star pyramid method declares and initializes an integer "n" with the specified number of rows. Next, define the initial count of the space as 0 and the initial count of the star as "n+

See all articles