Skip to content

Instantly share code, notes, and snippets.

@l-gu
Last active December 29, 2015 00:19
Show Gist options
  • Save l-gu/7585546 to your computer and use it in GitHub Desktop.
Save l-gu/7585546 to your computer and use it in GitHub Desktop.
Sort a list with a specific Comparator
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