【问题标题】:how to sort arraylist of java records如何对java记录的arraylist进行排序
【发布时间】:2023-02-24 02:23:26
【问题描述】:

我有这样的记录定义:

public record UserCourseSubscriptionRec(
    Integer userId,
    String userFirstName,
    String userLastName,
    Integer courseId,
    String courseName,
    Date startDate,
    Date endDate) {

}

我有一个记录的数组列表。

如何按 userId 升序然后 startDate 降序对这个 arrayList 进行排序?

我知道如何为一个班级做这件事,但我不能把这个记录改成一个班级。

【问题讨论】:

标签: java sorting record


【解决方案1】:

首先,您应该使用 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);

【讨论】:

  • 你也可以让record实现Comparable
  • 那是真实的。我将更新答案以提及它。
猜你喜欢
  • 2012-04-26
  • 2013-07-05
  • 2016-02-01
  • 1970-01-01
  • 2011-05-11
  • 2019-10-05
  • 2014-11-09
  • 2016-08-28
  • 1970-01-01
相关资源
最近更新 更多