1package beginnersbook.com;
2import java.util.*;
3public class Details {
4
5 public static void main(String args[]){
6 ArrayList<Student> arraylist = new ArrayList<Student>();
7 arraylist.add(new Student(101, "Zues", 26));
8 arraylist.add(new Student(505, "Abey", 24));
9 arraylist.add(new Student(809, "Vignesh", 32));
10
11 /*Sorting based on Student Name*/
12 System.out.println("Student Name Sorting:");
13 Collections.sort(arraylist, Student.StuNameComparator);
14
15 for(Student str: arraylist){
16 System.out.println(str);
17 }
18
19 /* Sorting on Rollno property*/
20 System.out.println("RollNum Sorting:");
21 Collections.sort(arraylist, Student.StuRollno);
22 for(Student str: arraylist){
23 System.out.println(str);
24 }
25 }
26}
1package beginnersbook.com;
2import java.util.Comparator;
3public class Student {
4 private String studentname;
5 private int rollno;
6 private int studentage;
7
8 public Student(int rollno, String studentname, int studentage) {
9 this.rollno = rollno;
10 this.studentname = studentname;
11 this.studentage = studentage;
12 }
13 ...
14 //Getter and setter methods same as the above examples
15 ...
16 /*Comparator for sorting the list by Student Name*/
17 public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
18
19 public int compare(Student s1, Student s2) {
20 String StudentName1 = s1.getStudentname().toUpperCase();
21 String StudentName2 = s2.getStudentname().toUpperCase();
22
23 //ascending order
24 return StudentName1.compareTo(StudentName2);
25
26 //descending order
27 //return StudentName2.compareTo(StudentName1);
28 }};
29
30 /*Comparator for sorting the list by roll no*/
31 public static Comparator<Student> StuRollno = new Comparator<Student>() {
32
33 public int compare(Student s1, Student s2) {
34
35 int rollno1 = s1.getRollno();
36 int rollno2 = s2.getRollno();
37
38 /*For ascending order*/
39 return rollno1-rollno2;
40
41 /*For descending order*/
42 //rollno2-rollno1;
43 }};
44 @Override
45 public String toString() {
46 return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
47 }
48
49}