"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Write a Custom Comparator Function in Java?

How to Write a Custom Comparator Function in Java?

Published on 2024-11-01
Browse:220

How to Write a Custom Comparator Function in Java?

1. Understanding the Basics of Comparator in Java

In Java, the Comparator interface provides a way to compare two objects to determine their order. This is especially useful when you want to sort collections like lists or arrays in a custom order.

A custom Comparator is needed when the natural ordering of objects (as defined by their Comparable implementation) doesn’t meet your needs. For example, sorting a list of Employee objects by salary, name, or age may require different comparators.

2. Writing a Custom Comparator Function

Let’s walk through the process of creating a custom Comparator.

2.1 Example: Sorting a List of Employees by Salary

Consider a class Employee with fields name , age , and salary. We want to sort a list of Employee objects by salary in ascending order.

import java.util.Comparator;

class Employee {
    private String name;
    private int age;
    private double salary;

    // Constructor, getters, and setters
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

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

class SalaryComparator implements Comparator {
    @Override
    public int compare(Employee e1, Employee e2) {
        return Double.compare(e1.getSalary(), e2.getSalary());
    }
}

In this example, the SalaryComparator class implements the Comparator interface and overrides the compare method to compare employees by their salary.

2.2 Demo: Sorting the Employee List

Now, let’s create a list of employees and sort it using our custom Comparator.

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

public class Main {
    public static void main(String[] args) {
        List employees = new ArrayList();
        employees.add(new Employee("John", 28, 50000));
        employees.add(new Employee("Anna", 32, 75000));
        employees.add(new Employee("Mike", 25, 45000));

        System.out.println("Before Sorting:");
        employees.forEach(System.out::println);

        // Sort employees by salary
        Collections.sort(employees, new SalaryComparator());

        System.out.println("
After Sorting by Salary:");
        employees.forEach(System.out::println);
    }
}

2.3 Result of the Demo

Running the above code will produce the following output:

Before Sorting:
Employee{name='John', age=28, salary=50000.0}
Employee{name='Anna', age=32, salary=75000.0}
Employee{name='Mike', age=25, salary=45000.0}

After Sorting by Salary:
Employee{name='Mike', age=25, salary=45000.0}
Employee{name='John', age=28, salary=50000.0}
Employee{name='Anna', age=32, salary=75000.0}

The list of employees is now sorted by their salary in ascending order, thanks to the custom Comparator.

3. Advanced Custom Comparators

Sometimes, you may need more complex comparison logic or want to sort by multiple fields.

3.1 Example: Sorting by Multiple Criteria

Let’s modify our Comparator to first sort by salary and then by name in case of a tie.

class SalaryThenNameComparator implements Comparator {
    @Override
    public int compare(Employee e1, Employee e2) {
        int salaryCompare = Double.compare(e1.getSalary(), e2.getSalary());
        if (salaryCompare == 0) {
            return e1.getName().compareTo(e2.getName());
        }
        return salaryCompare;
    }
}

3.2 Demo: Sorting by Salary and Name

Using the SalaryThenNameComparator , you can now sort employees by salary and name:

Collections.sort(employees, new SalaryThenNameComparator());

4. Conclusion

Writing a custom Comparator function in Java allows you to tailor the sorting behavior of collections to meet specific needs. Whether you need a simple comparison by a single field or a complex sorting by multiple criteria, Comparator provides a flexible and powerful solution.

If you have any questions or need further clarification, feel free to leave a comment below!

Read posts more at : How to Write a Custom Comparator Function in Java?

Release Statement This article is reproduced at: https://dev.to/anh_trntun_4732cf3d299/how-to-write-a-custom-comparator-function-in-java-198j?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3