首先,您应该使用 LocalDate 而不是 Date,因为后者已过时、已弃用且存在错误。 java.time 包中提供了该类和其他类,并提供了广泛的功能。
public record UserCourseSubscriptionRec(
Integer userId,
String userFirstName,
String userLastName,
Integer courseId,
String courseName,
Date startDate,
Date endDate) {
}
定义一个比较器。
Comparator<UserCourseSubscriptionRec> comp = Comparator
.comparing(UserCourseSubscriptionRec::userId)
.thenComparing(UserCourseSubscriptionRec::startDate,
Comparator.reverseOrder());
然后使用带有比较器的 ArrayList 排序方法。
YourList.sort(comp);
或者按照 cmets 中建议的f1sh,您可以让您的班级或记录实现ComparableHere 接口。这是它的样子。
record UserCourseSubscriptionRec(Integer userId, String userFirstName,
String userLastName, Integer courseId, String courseName,
Date startDate, Date endDate)
implements Comparable<UserCourseSubscriptionRec> { // implement the interface
public int compareTo(UserCourseSubscriptionRec ucs) {
// first, compare the userid's in ascending order
int result = userId.compareTo(ucs.userId);
// if non-zero, return the result.
// otherwise, return the result of sorting in reverse order
// (changing the `compareTo` argument order reverses the natural order).
return result != 0 ? result :
ucs.startDate.compareTo(startDate);
}
}
然后按如下方式调用排序。 null 参数表示使用由 Comparable 补充指定的顺序。
YourList.sort(null);