假設您的域對象名稱爲「員工」並且具有List<Employee>
作爲域對象列表。然後,您可以按如下方式通過比較器來使用Java 8排序功能。隨後,您將根據需要提取Min和Max。
employeeList.sort((Employee e1, Employee e2) -> e1.getUpdatedDate().compareTo(e2.getUpdatedDate()));
查找以下代碼示例以供參考。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
public class Main {
static DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx");
static Employee emp1 = new Employee(1, LocalDateTime.parse("2017-10-06 23:25:37+0000", format));
static Employee emp2 = new Employee(2, LocalDateTime.parse("2016-07-09 00:00:00+0000", format));
static Employee emp3 = new Employee(3, LocalDateTime.parse("2017-10-06 23:25:38+0000", format));
static Employee emp4 = new Employee(4, LocalDateTime.parse("2016-07-09 00:00:00+0000", format));
static List<Employee> employeeList = Arrays.asList(new Employee[] { emp1, emp2, emp3, emp4 });
public static void main(String[] args) {
employeeList.sort((Employee e1, Employee e2) -> e1.getUpdatedDate().compareTo(e2.getUpdatedDate()));
System.out.println("Max:" + employeeList.get(employeeList.size() - 1));
System.out.println("Min:" + employeeList.get(0));
System.out.println("==== Complete list ===");
employeeList.forEach(e -> System.out.println(e));
}
}
class Employee {
private int employeeNumber;
private LocalDateTime updatedDate;
public Employee() {
}
public Employee(int employeeNumber, LocalDateTime updatedDate) {
this.employeeNumber = employeeNumber;
this.updatedDate = updatedDate;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public LocalDateTime getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(LocalDateTime updatedDate) {
this.updatedDate = updatedDate;
}
public String toString() {
return String.format("Employee Number: %s, Updated Date: %s", this.employeeNumber, this.updatedDate);
}
}