1

I have the following list and I want to sort this whole list on the basis of the date how can I do this?

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

When I am using the following code it gives me an nullPointerException at o1.getDateTime()

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

EDITED

Now I am using the following code but it print the same data instaed of sorted data

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
    }
SFAH
  • 534
  • 1
  • 8
  • 24

1 Answers1

3

Try sorting it using:

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

syncdk
  • 2,820
  • 3
  • 25
  • 31