Comparator Interface in Java
The Comparator interface in Java is used to define custom comparison logic for objects that do not implement the Comparable interface or when you need to define multiple comparison criteria for the same class.
Usage
The Comparator interface is commonly used when you want to sort objects or perform comparisons based on specific criteria that are not defined by the natural ordering of the objects. By implementing the Comparator interface, you can provide a separate class or inline implementation to specify how the objects should be compared.
Methods
The Comparator interface consists of a single method:
int compare(T obj1, T obj2)
The compare
method compares two objects of type T and returns a negative integer, zero, or a positive integer to indicate whether the first object is less than, equal to, or greater than the second object, respectively.
The compare
method should follow these general rules:
- If
obj1
is less thanobj2
, return a negative integer. - If
obj1
is equal toobj2
, return zero. - If
obj1
is greater thanobj2
, return a positive integer.
Example
Here's an example that demonstrates the usage of the Comparator interface:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class AgeComparator implements Comparator>Person< {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
public class ComparatorExample {
public static void main(String[] args) {
List>Person< people = new ArrayList><();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 30));
Collections.sort(people, new AgeComparator());
for (Person person : people) {
System.out.println("Name: " + person.getName() + ", Age: " + person.getAge());
}
}
}
Output:
Name: Bob, Age: 20 Name: Alice, Age: 25 Name: Charlie, Age: 30
In this example, we create a class named "Person" without implementing the Comparable interface. We also create a separate class named "AgeComparator" that implements the Comparator interface. This comparator compares two Person objects based on their ages. In the main method, we create a list of Person objects, add three instances to it, and then sort the list using the Collections.sort method and the AgeComparator. The list is sorted based on the custom comparison logic defined by the AgeComparator, resulting in the output shown above.
Conclusion
The Comparator interface in Java allows you to define custom comparison logic for objects that do not implement the Comparable interface or when you need to specify multiple comparison criteria. By implementing the Comparator interface, you can provide separate classes or inline implementations to define how objects should be compared. This gives you greater flexibility in sorting and comparing objects based on specific criteria.
Example of sorting employees based on their salary using lambda expressions
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
public class LambdaSortExample {
public static void main(String[] args) {
List>Employee< employees = new ArrayList><();
employees.add(new Employee("Alice", 5000.0));
employees.add(new Employee("Bob", 3000.0));
employees.add(new Employee("Charlie", 4000.0));
Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary));
System.out.println("");
for (Employee employee : employees) {
System.out.println("- Name: " + employee.getName() + ", Salary: " + employee.getSalary() + "
");
}
System.out.println("
");
}
}
Output:
- Name: Bob, Salary: 3000.0
- Name: Charlie, Salary: 4000.0
- Name: Alice, Salary: 5000.0
In this example, we have a class named "Employee" with name and salary properties. In the main method, we create a list of Employee objects, add three instances to it, and then sort the list using the Collections.sort method and a lambda expression.
The lambda expression Comparator.comparingDouble(Employee::getSalary) specifies the comparison logic based on the salary of the Employee objects. The comparingDouble method takes a function that extracts the salary from the Employee object using a method reference (Employee::getSalary). This lambda expression acts as a comparator to compare the salaries of the Employee objects.
Finally, we iterate over the sorted list of employees and print their names and salaries using HTML tags to format the output as an unordered list.
This example demonstrates how to sort a list of objects based on a specific property using lambda expressions and the Comparator.comparing method. In this case, we sort the employees based on their salary.
I hope this example helps you understand how to sort employees based on their salary using lambda expressions in Java! Let me know if you have any further questions.
List Set Queue Map TreeMap Collection Comparable Interface Comparator Interface