Last active
December 19, 2015 08:08
-
-
Save oscarryz/5923101 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Date; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.text.SimpleDateFormat; | |
import java.text.ParseException; | |
class Employee { | |
String name; | |
String hireDate; | |
String hireHour; | |
static Employee hired( String name , String date, String hour ) { | |
Employee e = new Employee(); | |
e.name = name; | |
e.hireDate = date; | |
e.hireHour = hour; | |
return e; | |
} | |
public String toString() { | |
return String.format("name: %s, hire: %s %s%n", name, hireDate, hireHour ); | |
} | |
} | |
class CompareExample { | |
public static void main( String ... args ) { | |
List<Employee> list = Arrays.asList( | |
Employee.hired( "A", "01/01/2000" , "08:00" ), | |
Employee.hired( "B","01/01/2000" , "16:00" ), | |
Employee.hired( "C","01/01/1999" , "00:00" ), | |
Employee.hired( "D","24/02/2013" , "15:32" ), | |
Employee.hired( "E","08/07/2011" , "17:09" ), | |
Employee.hired( "F","08/07/2011" , "17:09" ) | |
); | |
Collections.sort( list, new Comparator<Employee>() { | |
public int compare( Employee a, Employee b ) { | |
try { | |
int result = toDate( a.hireDate ).compareTo( toDate( b.hireDate )); | |
return result != 0 ? result : toDate(a.hireHour).compareTo( toDate( b.hireHour)); | |
} catch ( ParseException e ) { | |
throw new RuntimeException( e ); | |
} | |
} | |
}); | |
System.out.println( list ); | |
} | |
static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm"); | |
private static Date toDate( String string ) throws ParseException { | |
return sdf.parse(string.length() == 10 ? string + " 00:00" : "01/01/1970 " + string); | |
} | |
} | |
// output | |
$ java CompareExample | |
[name: C, hire: 01/01/1999 00:00 | |
, name: A, hire: 01/01/2000 08:00 | |
, name: B, hire: 01/01/2000 16:00 | |
, name: E, hire: 08/07/2011 17:09 | |
, name: F, hire: 08/07/2011 17:09 | |
, name: D, hire: 24/02/2013 15:32 | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment