Untitled
unknown
java
a year ago
2.6 kB
2
Indexable
Never
import java.io.*; import java.util.*; @SuppressWarnings("unused") class Student { int roll_no, year, sem, age; String name; float fees; String branch; static String clg; public Student(int roll_no, String name, float fees, String branch, int year, int sem, int age){ this.roll_no = roll_no; this.name = name; this.fees = fees; this.branch = branch; this.year = year; this.sem = sem; this.age = age; clg = "PU"; } @Override public String toString() { return roll_no + " " + name + " " + fees + " " + branch + " " + year + sem + " " + age + " " + clg + "\n"; } } class AgeComparator implements Comparator<Object> { public int compare(Object o1, Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; if (s1.age == s2.age) return 0; else if (s1.age > s2.age) return 1; else return -1; } } class NameComparator implements Comparator<Object> { public int compare(Object o1, Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; return s1.name.compareTo(s2.name); } } class FeesComparator implements Comparator<Object> { public int compare(Object o1, Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; if (s1.fees == s2.fees) return 0; else if (s1.fees > s2.fees) return 1; else return -1; } } public class Temp1 { public static void main(String args[]) { ArrayList<Student> s1 = new ArrayList<Student>(); s1.add(new Student(1, "Shiva", 10000.00f, "cse", 1, 1, 18)); s1.add(new Student(2, "Venky", 15000.00f, "ise", 1, 2, 20)); s1.add(new Student(3, "Jesus", 17000.00f, "ece", 1, 1, 19)); s1.add(new Student(3, "Alla", 12000.00f, "eee", 1, 1, 19)); s1.add(new Student(3, "Budha", 11000.00f, "mech", 1, 1, 21)); System.out.println("Sorting by Name"); System.out.println("---------------"); Collections.sort(s1, new NameComparator()); Iterator<Student> itr = s1.iterator(); while(itr.hasNext()) { Student st = (Student)itr.next(); System.out.println(st.toString()); } System.out.println("Sorting by Age"); System.out.println("---------------"); Collections.sort(s1, new AgeComparator()); Iterator<Student> itr1 = s1.iterator(); while(itr1.hasNext()) { Student st = (Student)itr1.next(); System.out.println(st.toString()); } System.out.println("Sorting by Fees"); System.out.println("---------------"); Collections.sort(s1, new FeesComparator()); Iterator<Student> itr2 = s1.iterator(); while(itr2.hasNext()) { Student st = (Student)itr2.next(); System.out.println(st.toString()); } } }