Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

java - How to Sort an Arraylist of Date in ascending and descending order which is in String format

I have arrayLists of Dates which is in String format then how can I sort this arraylists,

ArrayList<String> aryBeginDate;
ArrayList<String> aryDueDate;

for (int i = 0; i < arySubject.size(); i++) {

    RowItem row = new RowItem();
    row.setSubject(arySubject.get(i).toString());
    row.setUser(aryFromUser.get(i).toString());

    if (aryBeginDate.equals(" ")) {
        row.setStartDate(" ");
    } else {
        row.setStartDate(aryBeginDate.get(i).toString()); \Have to sort at this line
    }

    if (aryDueDate.equals(" ")) {
        row.setEndDate(" ");
    } else {
        row.setEndDate(aryDueDate.get(i).toString()); \Have to sort at this line
    }

    aryListBean.add(row);

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use a String when you want a Date. Use a Date. You should only transfom the Date to a String when displaying it. Otherwise, everywhere in the code, the date should of type Date. This is what allows sorting in chronological order, because dates have a natural order which is chronological.

So, once the RowItem has a startDate and an endDate, both being of type Date, you can sort a list of row items by start date using a simple comparator:

Collections.sort(rowItems, new Comparator<RowItem>() {
    @Override
    public int compare(RowItem r1, RowItem 2) {
        return r1.getStartDate().compareTo(r2.getStartDate());
    }
}); 

Also, fix your indentationof if/else blocks, because your way is really not readable:

if (aryBeginDate.equals(" ")) {
    row.setStartDate(" ");
} 
else {
    row.setStartDate(aryBeginDate.get(i).toString());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...