gpt4 book ai didi

java - Collections.sort 按列表中对象的日期属性排序

转载 作者:行者123 更新时间:2023-12-01 23:16:02 25 4
gpt4 key购买 nike

如何使用 Collections.sort 对具有以下属性的对象列表进行排序?

我想按日期对列表进行排序。

public Comment {
private Timestamp date;
private String description;

}

当然,也有 getter 和 setter。

谢谢!

最佳答案

您有 2 个选项可以创建 Comparator用于创建排序策略,或定义实现 Comparable 的类的自然顺序

使用比较器的示例:

public class Comment{

private Timestamp date;
private String description;
public static final Comparator<Comment> commentComparator = new MyComparator();

//getter and setter

static class MyComparator implements Comparator<Comment>{

@Override
public int compare(Comment o1, Comment o2) {
// here you do your business logic, when you say where a comment is greater than other
}
}

}

并在客户端代码中。

示例:

List<MyClass> list = new ArrayList<>();
//fill array with values
Collections.sort(list, Comment.commentComparator );

了解更多:Collections#sort(..)

如果您想定义类的自然顺序,只需定义

public class Comment implements Comparable<Comment>{

@Override
public int compareTo(Comment o) {
// do business logic here
}
}

在客户端代码中:

   Collections.sort(myList); // where myList is List<Comment>

关于java - Collections.sort 按列表中对象的日期属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com