How to order an Arraylist in ascending order by date

Asked

Viewed 1,329 times

-1

I need to order a ArrayList in ascending order by date. For I keep adding values out of order in it. In my ArrayList has only two fields in each element: data and valor. Does anyone know any method I can use?

  • Edit the question and add what you’ve already done.

1 answer

3


You can use the method sort of the Collections class. The example below has been adapted of Soen’s reply:

Collections.sort(suaLista, new Comparator<SeuObjeto>() {
  public int compare(SeuObjeto o1, SeuObjeto o2) {
      if (o1.getDate() == null || o2.getDate() == null)
        return 0;
      return o1.getDate().compareTo(o2.getDate());
  }
});
  • I managed to do what I wanted using this scheme there. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.