我有一个名为channelsList的频道列表。
List<Channel> channelsList;
频道类
public class Channel{
public Conversation conversation;
}
会话班
public class Conversation{
public String sentAt;
}
我需要按照myDate的降序对频道列表进行排序。我怎样才能使用比较器呢?到目前为止我试过这个。但这不起作用,因为我的收集频道可以具有会话的空值,并且会话可以具有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);
}
}
});
答案 0 :(得分:0)
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);
}
}
});
答案 1 :(得分:0)
您可以使用比较器或类似物来对数组进行排序