Wednesday, June 22, 2016

Comparable implemention for sorting

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class Student implements Comparable {
String firstName, lastName;

public Student(String f, String l) {
this.firstName = f;
this.lastName = l;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public String toString() {
return "[dept=" + firstName + ",name=" + lastName + "]";
}

public int compareTo(Object obj) {
Student emp = (Student) obj;
int deptComp = firstName.compareTo(emp.getFirstName());

return ((deptComp == 0) ? lastName.compareTo(emp.getLastName()) : deptComp);
}



public static void main(String args[]) {
Student emps[] = { new Student("Debbie", "Degree"), new Student("Geri", "Grade"),
new Student("Ester", "Extent"), new Student("Mary", "Measure"), new Student("Anastasia", "Amount"),new Student("Debbie", "Aegree") };
Set set = new TreeSet(Arrays.asList(emps));
System.out.println(set);
}
}

No comments:

Post a Comment