使用compartor的Java Date排序

时间:2017-05-01 14:55:41

标签: java sorting date collections comparator

我正在尝试对日期列表进行排序,但它无效。

这是AttemptEntity中的声明和获取功能

        List<AttemptEntity> attempts = called.getAttempts();
        Collections.sort(attempts, new Comparator<AttemptEntity>() {
        @Override
        public int compare(AttemptEntity a1, AttemptEntity a2) {
            if (a1.getEndTime() == null || a2.getEndTime() == null)
                return 0;
            return a1.getEndTime().compareTo(a2.getEndTime());
            }
        });

这是没有做任何事情的排序代码。 GetAttempts()获取所有被调用尝试的列表。它们不合适,我只是希望能够得到最新的endTime。

Comparator<AttemptEntity> comparator = Comparator.comparing(AttemptEntity::getEndTime).reversed();
attempts.sort(comparator);

我相信上面的代码应该排序尝试,然后在尝试之后应该排序,所以最新的结束时间是attempts.get(attempts.size() - 1).getEndTime()

我尝试使用以下内容,而且根本没有进行任何排序。输入列表和输出列表完全相同。

{{1}}

1 个答案:

答案 0 :(得分:0)

我的代码中的一切看起来都不错,所以尝试使用您的代码,我可以将日期排序,让我知道您是否做了与下面不同的事情:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class DateSorter {
    static List<AttemptEntity> attempts = null;
    public static void main(String[] args) {
        prepareTestData();
        System.out.println(attempts);
        sortDates();
        System.out.println(attempts);
    }

    private static void sortDates() {
        Collections.sort(attempts, new Comparator<AttemptEntity>() {
            @Override
            public int compare(AttemptEntity a1, AttemptEntity a2) {
                if (a1.getEndTime() == null){
                    return 0;
                } else if(a2.getEndTime() == null){
                    return -1;
                }
                return a1.getEndTime().compareTo(a2.getEndTime());
            }
        });
    }

    private static void prepareTestData() {
        attempts = new ArrayList<>();
        attempts.add(new AttemptEntity(new Date(4444)));
        attempts.add(new AttemptEntity(new Date(1111)));
        attempts.add(new AttemptEntity(null));
        attempts.add(new AttemptEntity(new Date(3333)));
        attempts.add(new AttemptEntity(new Date(2222)));
    }
}

测试POJO:

import java.util.Date;

public class AttemptEntity {

    private Date endTime;

    AttemptEntity(Date date){
        endTime = date;
    }

    public Date getEndTime() {
        return endTime;
    }

    @Override
    public String toString() {
        return endTime == null ? null : endTime.toString();
    }

}

最终输出:

[Thu Jan 01 05:30:04 IST 1970, Thu Jan 01 05:30:01 IST 1970, null, Thu Jan 01 05:30:03 IST 1970, Thu Jan 01 05:30:02 IST 1970]
[Thu Jan 01 05:30:01 IST 1970, Thu Jan 01 05:30:02 IST 1970, Thu Jan 01 05:30:03 IST 1970, Thu Jan 01 05:30:04 IST 1970, null]

更新:看起来某些NULL日期可能会导致一些排序问题,我已更新上述代码中的compare方法。