Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Collections API

Searching and Comparator

Java provides the Collections API, which includes interfaces and classes to work with collections of objects. For example, for searching in collection

Searching can be performed using Collections.binarySearch() for sorted lists or by implementing custom search logic.

Example: Searching in a Sorted List

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

public class SearchingExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(8);

        int index = Collections.binarySearch(numbers, 5);
        if (index >= 0) {
            System.out.println("Element found at index: " + index); // Output: Element found at index: 1
        } else {
            System.out.println("Element not found.");
        }
    }
}

Custom Searching Using Collections API in Java:

In Java, you can create a custom searching logic by implementing the Comparator interface. The Comparator interface allows you to define custom comparison logic for objects. You can then use this custom Comparator to perform searching operations on collections. Here's a detailed explanation along with an example code:

1. Creating a Custom Comparator:

First, create a custom Comparator for your custom searching logic. For example, if you want to search strings based on their lengths, you can create a Comparator like this:

javaCopy codeimport java.util.Comparator;

class StringLengthComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
}

In this example, StringLengthComparator compares strings based on their lengths.

2. Using Custom Comparator for Searching:

You can use the custom Comparator with methods like Collections.binarySearch() to perform searching on collections. Here's an example of how you can do it:

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

public class CustomSearchingExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("apple");
        words.add("banana");
        words.add("cherry");
        words.add("date");
        words.add("grape");

        // Sort the list using the custom comparator
        Collections.sort(words, new StringLengthComparator());

        // Perform custom searching (searching by length)
        String searchTerm = "date";
        int index = Collections.binarySearch(words, searchTerm, new StringLengthComparator());

        if (index >= 0) {
            System.out.println("Word '" + searchTerm + "' found at index: " + index);
        } else {
            System.out.println("Word '" + searchTerm + "' not found.");
        }
    }
}

Output:

perlCopy codeWord 'date' found at index: 1

Explanation:

  • Custom Comparator:

    • StringLengthComparator is a custom Comparator that compares strings based on their lengths.

  • Using Custom Comparator:

    • The Collections.sort() method sorts the list of strings using the custom StringLengthComparator.

    • The Collections.binarySearch() method performs a binary search based on the string length using the same custom comparator.

  • Result:

    • The word "date" is found at index 1 in the sorted list because it has a length of 4.

In this example, you have created a custom Comparator for searching strings based on their lengths. You can create different custom comparators for different searching criteria according to your requirements. This approach allows you to perform custom searching operations on collections in Java.

PreviousSorting and ComparableNextIntroduction and Life Cycle

Last updated 1 year ago