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

Sorting and Comparable

Java provides the Collections API, which includes interfaces and classes to work with collections of objects, one of them is for sorting collection.

Using Collections API to Sort a List

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

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

        Collections.sort(numbers);

        System.out.println("Sorted List: " + numbers); // Output: [2, 5, 8]
    }
}

In Java, the Comparable interface is used to define the natural ordering of objects. Objects of a class implementing the Comparable interface can be compared and sorted based on a natural order defined by the class itself. This interface contains a single method: compareTo(Object obj). Here's a detailed explanation along with an example code:

1. Comparable Interface:

  • compareTo(Object obj) Method:

    • This method compares the current object with the specified object for order.

    • It returns a negative integer, zero, or a positive integer if the current object is less than, equal to, or greater than the specified object, respectively.

Example: Implementing Comparable for Sorting Custom Objects

Suppose you have a Person class:

javaCopy codeclass Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int compareTo(Person person) {
        return this.age - person.age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

In this example, the Person class implements the Comparable interface. The compareTo() method compares Person objects based on their ages.

2. Usage in Sorting using Comparable:

You can use the compareTo() method to sort objects of the class implementing the Comparable interface using sorting methods like Collections.sort().

Example: Sorting a List of Persons

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

public class ComparableExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        System.out.println("Before sorting:");
        System.out.println(people);

        Collections.sort(people);

        System.out.println("\nAfter sorting by age:");
        System.out.println(people);
    }
}

Output:

lessCopy codeBefore sorting:
[Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]

After sorting by age:
[Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]

In this example, the Collections.sort() method sorts the list of Person objects based on their ages due to the natural ordering defined by the compareTo() method in the Person class.

Explanation:

  • Implementing the Comparable interface allows objects of a class to be compared and sorted based on the defined natural order.

  • The compareTo() method returns a negative value if the current object is less than the specified object, zero if they are equal, and a positive value if the current object is greater.

  • Sorting methods like Collections.sort() use the compareTo() method for sorting objects of the implementing class.

PreviousThread Pools and ExecutorsNextSearching and Comparator

Last updated 1 year ago