JAVA:如何在字段的基础上对列表进行排序

时间:2017-11-21 11:39:02

标签: java sorting date time

我有以下列表,我想根据日期对整个列表进行排序,我该怎么做?

List<DevicePing> devicePing=Arrays.asList(
                new DevicePing(1L,2017-11-21 10:10:10.0),
                new DevicePing(2L,2017-11-21 10:00:00.0),
                new DevicePing(3L,2017-11-21 10:15:10.0),
                new DevicePing(4L,2017-11-21 09:30:10.0),
                new DevicePing(5L,2017-11-21 09:45:10.0),
                new DevicePing(6L,2017-11-21 09:50:10.0),
                new DevicePing(7L,2017-11-21 09:55:10.0);

当我使用以下代码时,它在o1.getDateTime()

给我一​​个nullPointerException
Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

EDITED

现在我使用以下代码,但它打印了与排序数据相同的数据

public void calculateTimesheet(RiderLocation riderLocation,List<DevicePing> devicePing,List<RiderAvailability> riderAvailability)
    {
        devicePing.sort(Comparator.comparing(DevicePing::getDate));
        for(DevicePing dp:devicePing)
        {
            System.out.println("dp: " + dp);
        }
    }

DevicePing.java

@Entity
public class DevicePing {

    public DevicePing(Long id ,Date createdAt) {
        this.id = id;
        this.createdAt = createdAt;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private User rider;

    @Column( nullable = false,columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    //getter nad setter
    }

1 个答案:

答案 0 :(得分:3)

尝试使用以下方法对其进行排序:

devicePing.sort(Comparator.comparing(DevicePing::getDateTime));