import java.util.*; class Student1 { String name; int id; double perc; Student1(int id, String name, double perc){ this.id = id; this.name = name; this.perc = perc; } void display() { System.out.println(id + "\t" + name + "\t" + perc); } } class StudNameSort implements Comparator{ @Override public int compare(Student1 rc, Student1 kr) { // TODO Auto-generated method stub return rc.name.compareTo(kr.name); } } class StudIdSort implements Comparator{ @Override public int compare(Student1 rc, Student1 kr) { // TODO Auto-generated method stub if(rc.id == kr.id) return 0; else if(rc.id > kr.id) return 1; else return -1; } } public class ComparatorDemo { public static void main(String[] args) { // TODO Auto-generated method stub Student1 s1 = new Student1(526,"Raju", 97.67); Student1 s2 = new Student1(556,"Ramu", 77.67); Student1 s3 = new Student1(546,"Raju", 67.67); Student1 s4 = new Student1(536,"Chythu", 87.67); ArrayList al = new ArrayList(); al.add(s1); al.add(s2); al.add(s3); al.add(s4); System.out.println("Before Sorting: "); Iterator i = al.iterator(); while(i.hasNext()) { Student1 s = (Student1)i.next(); s.display(); } System.out.println("After Name-wise Sorting: "); Collections.sort(al,new StudNameSort()); Iterator i1 = al.iterator(); while(i1.hasNext()) { Student1 s = (Student1)i1.next(); s.display(); } System.out.println("After Id-wise Sorting: "); Collections.sort(al,new StudIdSort()); Iterator i2 = al.iterator(); while(i2.hasNext()) { Student1 s = (Student1)i2.next(); s.display(); } } }