2017-05-01 27 views
1

我想排序日期列表,它不工作。Java日期排序使用分区

下面是声明和AttemptEntity

@Temporal(TemporalType.TIMESTAMP) 
@Column(name = "end_time") 
private Date endTime; 

public Date getEndTime() { 
    return endTime; 
} 

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

 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()); 
      } 
     }); 

我相信,上面的代码应该那么它应该尝试进行排序后进行分类的尝试,并且,所以最晚结束时间将attempts.get(attempts.size() - 1).getEndTime()

我试图使用以下,并没有做任何分类。输入列表和输出列表完全相同。

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

如果有没有'endTime'的尝试,它会被'compare'方法视为等于_every_其他实例。我不确定这样的通配符会对二进制排序过程产生什么影响。 – jingx

回答

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] 

更新:看起来有些空日期可能造成一些排序的问题,我已经更新在上面的代码compare方法。