Java 字符串日期比较器

Java String date comparator

我有一个频道列表,名为 channelsList。

List<Channel> channelsList;

频道Class

public class Channel{
    public Conversation conversation;
}

对话Class

public class Conversation{
    public String sentAt;
}

我需要按照 myDate 的降序对频道列表进行排序。我该如何使用比较器?到目前为止我试过了。但这是行不通的,因为我的集合 Channel 可以为会话设置空值,而 Conversation 可以为 sentAt 设置空值。任何帮助将不胜感激。

 Collections.sort(channelsList, new Comparator<Channel>() {
        DateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);

        @Override
        public int compare(Channel o1, Channel o2) {
            try {
                if (o1.getConversation() != null && Util.isUTCFormat(o1.getConversation().getSentAt()) && o2.getConversation() != null && Util.isUTCFormat(o2.getConversation().getSentAt()))
                    return format.parse(o1.getConversation().getSentAt()).compareTo(format.parse(o2.getConversation().getSentAt()));
                else
                    return -1;

            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }              
        }
    });
Collections.sort(channelsList, new Comparator<Channel>() {
    DateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);

    @Override
    public int compare(Channel o1, Channel o2) {
        // If both are null, they are equal
        if (o1.getConversation() == null && o2.getConversation() == null)
            return 0;

        // If only first one is null, it is less than the other (null's come first)
        if (o1.getConversation() == null)
            return -1;

        // If only second one is null, it is greater than the other
        if (o2.getConversation() == null)
            return 1;

        Conversation c1 = o1.getConversation();
        Conversation c2 = o2.getConversation();

        // Same comparisons are done here again
        if (c1.getSentAt() == null && c2.getSentAt() == null)
            return 0;

        if (c1.getSentAt() == null)
            return -1;

        if (c2.getSentAt() == null)
            return 1;

        try {
            if (Util.isUTCFormat(o1.getConversation().getSentAt()) && Util.isUTCFormat(o2.getConversation().getSentAt()))
                return format.parse(o1.getConversation().getSentAt()).compareTo(format.parse(o2.getConversation().getSentAt()));
            else
                return -1;

        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }              
    }
});

您可以使用 comparator 或 comparable 对数组进行排序