Last active
December 29, 2015 00:19
-
-
Save l-gu/7585546 to your computer and use it in GitHub Desktop.
Sort a list with a specific Comparator
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
public static void main(String[] args) { | |
List<Student> list = new LinkedList<Student>(); | |
int i = 1 ; | |
list.add(new Student(i++,"John","Wayne")); | |
list.add(new Student(i++,"Joe","Dalton")); | |
list.add(new Student(i++,"Bart","Simpson")); | |
list.add(new Student(i++,"Homer","Simpson")); | |
list.add(new Student(i++,"Jack","Dalton")); | |
System.out.println("Sort by first name"); | |
Collections.sort(list, new Comparator<Student>() { | |
public int compare(Student s1, Student s2) { | |
String firstName = s1.getFirstName() ; | |
if ( firstName != null ) { | |
return firstName.compareTo(s2.getFirstName()); | |
} | |
return -1; | |
} | |
}); | |
print(list); | |
System.out.println("Sort by id"); | |
Collections.sort(list, new Comparator<Student>() { | |
public int compare(Student s1, Student s2) { | |
return s1.getId() - s2.getId() ; | |
} | |
}); | |
print(list); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment