list中的每一个元素是一个封装的类对象,如下ConstructMessage就是一个消息的封装类;?msent就是消息的发送时间。将一个包含多个消息的集合list进行发送时间排序。
public class ConstructMessage {
private String msent;
private String Id;
private String event;
private String headline;
private String description;
public void setMsent(String msent) {
this.msent = msent;
}
public String getMsent() {
return msent;
}
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
首先先做一个比较的方法类:
class dateCampare implements Comparator<ConstructMessage> {
@Override
public int compare(ConstructMessage s1, ConstructMessage s2) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date dt1 = df.parse(s1.getMsent());
Date dt2 = df.parse(s1.getMsent());
if (dt1.getTime() < dt2.getTime()) {
return -1;
} else if (dt1.getTime() > dt2.getTime()) {
return 1;
} else {
return 0;
}
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
定义一个集合用来装消息。
List<ConstructMessage> list2=new ArrayList<ConstructMessage>()
通过Collections.sort(list, comparator)将list中的消息按照上面的比较方式进行排序,调用以下方法可以实现。返回的是排过序的集合。
public static List<ConstructMessage> MessageTimeSorting(List<ConstructMessage> list){
List<ConstructMessage> list2=new ArrayList<ConstructMessage>();
dateCampare comparator=new dateCampare();
Collections.sort(list, comparator);
for(int i=list.size()-1;i>=0;i--){
Log.e(TAG,"Ipaws Time sort result time: "+list.get(i).getMsent()+"\nid="+list.get(i).getId()+"\nheadline="+list.get(i).getHeadline());
}
return list;
}
|