如何使用Collections.sort对具有以下属性的对象列表进行排序?
我想按日期对列表进行排序。
public Comment {
private Timestamp date;
private String description;
}
当然,也有吸气剂和制定者。
谢谢!
答案 0 :(得分:2)
您有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>
答案 1 :(得分:1)
使用比较器,例如:
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CommentComparator implements Comparator<Comment> {
@Override
public int compare(Comment o1, Comment o2) {
return o1.getDate().compareTo( o2.getDate() );
}
public static void main(String[] args) {
List<Comment> list = new ArrayList<Comment>();
for (int i = 0; i < 10; i++) {
Timestamp t = new Timestamp( System.currentTimeMillis() );
Comment c = new Comment();
c.setDate(t);
c.setDescription( String.valueOf(i) );
list.add(c);
}
Collections.sort(list, new CommentComparator());
}
}