Friday 17 February 2012

sort objects with comparable


package com.usr.collections;

public class Employee implements Comparable<Employee> {
       private String firstName;
       private String lastName;

       public Employee(String firstName, String lastName) {
              super();
              this.firstName = firstName;
              this.lastName = lastName;
       }

       public String getFirstName() {
              return firstName;
       }

       public String getLastName() {
              return lastName;
       }

       public int compareTo(Employee obj) {
              Employee e = (Employee) obj;
              return this.firstName.compareTo(e.getFirstName());
       }

}
package com.usr.collections;

import java.util.ArrayList;

import java.util.Collections;
import java.util.List;

public class ComparableTest {
       static List<Employee> empList = new ArrayList<Employee>();

       public static void main(String[] args) {

              empList.add(new Employee("Berry", "Alex"));
              empList.add(new Employee("Tony", "Blair"));
              empList.add(new Employee("Alex", "Berry"));
              empList.add(new Employee("Blair", "Tony"));
              displayEmpList(empList);
              System.out.println(".....................");

              Collections.sort(empList);
              System.out.println("After sorting");
              System.out.println("........................");
              displayEmpList(empList);

       }

       private static void displayEmpList(List<Employee> list) {
              for (Employee emp : empList) {
                     System.out.println(emp.getFirstName());
              }

       }
}


OUTPUT 
Berry
Tony
Alex
Blair
.....................
After sorting
........................
Alex
Berry
Blair
Tony
 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.