Sort an Array of dates in ascending order using Custom Comparator | Java implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver code
import java . util . * ; import java . lang . * ; class GFG { if ( year2 . compareTo ( year1 ) > 0 ) return - 1 ; else if ( year2 . compareTo ( year1 ) < 0 ) return 1 ; else if ( month2 . compareTo ( month1 ) > 0 ) return - 1 ; else if ( month2 . compareTo ( month1 ) < 0 ) return 1 ; else if ( day2 . compareTo ( day1 ) > 0 ) return - 1 ; else return 1 ; } } ) ; static void printDatesAscending ( ArrayList < String > arr ) { Collections . sort ( arr , new Comparator < > ( ) { public int compare ( String date1 , String date2 ) { String day1 = date1 . substring ( 0 , 2 ) ; String month1 = date1 . substring ( 3 , 5 ) ; String year1 = date1 . substring ( 6 ) ; String day2 = date2 . substring ( 0 , 2 ) ; String month2 = date2 . substring ( 3 , 5 ) ; String year2 = date2 . substring ( 6 ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) System . out . println ( arr . get ( i ) ) ; } public static void main ( String [ ] args ) { ArrayList < String > arr = new ArrayList < > ( ) ; arr . add ( "25-08-1996" ) ; arr . add ( "03-08-1970" ) ; arr . add ( "09-04-1994" ) ; arr . add ( "29-08-1996" ) ; arr . add ( "14-02-1972" ) ; printDatesAscending ( arr ) ; } }