Skip to content Skip to sidebar Skip to footer

Sort Arraylist Of Calendars

I have a list of objects containing hours and minutes. The list is in a chaotic order and I need to sort them by the hour from 00:00 to 23:59. The object is public class ProgramIte

Solution 1:

I believe the the theme is not calendar sorting. If so then do not allocate more memory using Calender object, add this method simply,

publicclassProgramItem {
   ....
   intgetAsMins() {
      return hours *60 + mins;
   }
}
....
Collections.sort(items, new Comparator<ProgramItem>() {
        publicintcompare(ProgramItem item1, ProgramItem item2) {
           return item1.getAsMins() - item2.getAsMins();
        }
});

Solution 2:

Add this rule to the comparator:

Collections.sort(items, new Comparator<ProgramItem>() {
        publicintcompare(ProgramItem item1, ProgramItem item2) {
            if (item1.getCalendar().get(Calendar.HOUR) == 0 && item1.getCalendar().get(Calendar.MINUTE) == 0) {
                return-1
            } 
            if (item1.getCalendar().before(item2.getCalendar())) {
                return-1;
            } else {
                return1;
            }
        }
})

Post a Comment for "Sort Arraylist Of Calendars"