How to use comparator in java?
import java.util.*;
class ComparatorTest {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(new Employee("B", 3));
list.add(new Employee("A", 1));
list.add(new Employee("C", 2));
Collections.sort(list, new EmployeeComparator());
for (Employee emp : list) {
System.out.println(emp.name + "\t" + emp.age);
}
}
}
class EmployeeComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
if (o1.age > o2.age) {
return -1;
} else {
return 1;
}
}
}
class Employee {
String name;
int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
}
Comments
Post a Comment