How to sort an ArrayList in ascending order by date

-1

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

    
asked by anonymous 28.03.2018 / 01:47

1 answer

3

You can use the sort method of the Collections class. The example below has been adapted from this SOEn response :

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());
  }
});
    
28.03.2018 / 02:10