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

标签 java sorting

如何使用 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/

相关文章:

java - Webflux + Webclient + Netty,如何使用带有多个客户端证书的SslContext?

Dart 中的 List.shuffle() ?

c - 在 C 中对二维数组的行进行排序

java - 按字符串属性对自定义类型数组进行排序?

arrays - 如何在 Bash 中按降序对字符串数组进行排序?

java - OBJ 加载 - 奇怪的法线/uv

java - jackson :使用 [Ljava.lang.Double 的 InvalidDefinitionException

java - HQL 按日期查询(Java+NetBeans)

java - 开发使用 AppEngine 数据库的 Java 应用程序

java - 按扩展名和 Java 网站名称的字母顺序对网站名称进行排序