comparator interface 可以被用作集合外部實現的排序。
它是在java.util package。
它有兩個methods:
分別是compare(Object obj1, Object obj2)
和equals(Object element)
我們可以利用Comparator去為物件的屬性重新排序(例如 ID號碼、名字、電話等等)。
而且完成Comparator的資料可以通過Collections.sort 或者Arrays.sort實現排序。
compare()
public interface Comparator<T> {
int compare(T o1, T o2);
}
• 一個負數,即是第一個參數比第二個小。
• 零,即是第一個參數等於第二個。
• 一個正數,即是第一個參數比第二個大。
例子:
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1010, "Atom", 100000.00, LocalDate.of(2020, 1, 1)));
employees.add(new Employee(1004, "Ben", 95000.50, LocalDate.of(2020, 1, 11)));
employees.add(new Employee(1015, "Coco", 134000.00, LocalDate.of(2020, 1, 28)));
employees.add(new Employee(1009, "Doggy", 100000.00, LocalDate.of(2020, 1, 18)));
System.out.println("Employees : " + employees);
// 按員工的名字排序
Comparator<Employee> employeeNameComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
};
Collections.sort(employees, employeeNameComparator);
System.out.println("\nEmployees (Sorted by Name) : " + employees);
//按員工的工資排序
Comparator<Employee> employeeSalaryComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
if(e1.getSalary() < e2.getSalary()) {
return -1;
} else if (e1.getSalary() > e2.getSalary()) {
return 1;
} else {
return 0;
}
}
};
Collections.sort(employees, employeeSalaryComparator);
System.out.println("\nEmployees (Sorted by Salary) : " + employees);
//按員工加入的日期排序
Comparator<Employee> employeeJoiningDateComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getJoiningDate().compareTo(e2.getJoiningDate());
}
};
Collections.sort(employees, employeeJoiningDateComparator);
System.out.println("\nEmployees (Sorted by JoiningDate) : " + employees);
}
}
參考文章/網站/書本: