任何人都可以共享逻辑来对LocalDateTime进行排序,并从域对象列表中获取最大和最小记录。
域对象 -
private int employeeNumber;
private LocalDateTime updatedDate;
第一记录
1.1,2016-07-09 00:00:00+0000
2.2,2017-10-06 23:25:37+0000
最大输出:2,2017-10-06 23:25:37 + 0000
最低产出:1,2016-07-09 00:00:00 + 0000
答案 0 :(得分:5)
您的简化数据集
sql = "UPDATE `Camper` SET `amountPaid` = ? where id like ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, newAmountPaid);
ps.setString(2, playerId + "%");
ps.executeUpdate();
将hashset转换为stream并从中生成min和max
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx");
dates.add(LocalDateTime.parse("2016-07-09 00:00:00+0000", fmt));
dates.add(LocalDateTime.parse("2017-10-06 23:25:37+0000", fmt));
输出:
Min:2016-07-09T00:00
Max:2017-10-06T23:25:37
您现在可以轻松地将此核心逻辑调整到您的方案中。
答案 1 :(得分:0)
假设您的域对象名称为“Employee”,并将List<Employee>
作为域对象列表。然后,您可以通过传递Comparator来使用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);
}
}