_Csandeep

Java Comparable Vs. Comparator

Aug 28th, 2015 (edited)
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.92 KB | None | 0 0
  1. package com.stackoverflow.questions.Q1440134;
  2.  
  3. import org.jetbrains.annotations.NotNull;
  4.  
  5. import java.util.Arrays;
  6. import java.util.Collections;
  7. import java.util.Comparator;
  8. import java.util.List;
  9.  
  10. /**
  11. * @see [http://stackoverflow.com/questions/1440134/when-should-a-class-be-comparable-and-or-comparator]
  12. * @see [http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html]
  13. * @see [http://java-journal.blogspot.in/2011/01/when-to-use-comparable-and-when-to-use.html]
  14. * <p>
  15. * If we have only one single sorting criteria to sort our elements then we can use 'Comparable'
  16. * but if we have more than one sorting criterias then we have to go for 'Comparator' "also".
  17. * <p>
  18. * Said differently, it's more that we use 'Comparable' if there is only one single obvious thing to compare on.
  19. * And even then we can just write a 'Comparator'. If we have two different programs using the same class,
  20. * and one wants to sort by just age and the other by just name, at least one of them will need to use a
  21. * Comparator.
  22. * <p>
  23. * java.lang.Comparable: int compareTo(Object o1)
  24. * ----------------------------------------------
  25. * This method compares this object with o1 object. Returned int value has the following meanings.
  26. * 1. positive – this object is greater than o1
  27. * 2. zero – this object equals to o1
  28. * 3. negative – this object is less than o1
  29. * <p>
  30. * java.util.Comparator: int compare(Object o1, Objecto2)
  31. * ------------------------------------------------------
  32. * This method compares o1 and o2 objects. Returned int value has the following meanings.
  33. * 1. positive – o1 is greater than o2
  34. * 2. zero – o1 equals to o2
  35. * 3. negative – o1 is less than o2
  36. */
  37. public class ComparableVsComparator {
  38.     public static void main(String[] args) {
  39.         List<Employee> employeeList = createEmployeesAndAddThemToAList();
  40.         System.out.println(employeeList.size() + " employees created!");
  41.         System.out.println("EMPLOYEE LIST(UNSORTED):");
  42.         employeeList.forEach(System.out::println);
  43.        
  44.         System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
  45.        
  46.         /**
  47.         * Sorting in natural ordering
  48.         */
  49.         Collections.sort(employeeList);
  50.         System.out.println("EMPLOYEE LIST(SORTED AS PER NATURAL ORDER):");
  51.         employeeList.forEach(System.out::println);
  52.        
  53.         System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
  54.        
  55.         /**
  56.         * Sorting Employee types by other fields(for example: sort by 'age'
  57.         * See 'AgeComparator' which sorts Employees by their age by implementing
  58.         * 'java.util.Comparator'
  59.         */
  60.         System.out.println("EMPLOYEE LIST(SORTED BY AGE):");
  61.         Collections.sort(employeeList, new AgeComparator());
  62.         employeeList.forEach(System.out::println);
  63.        
  64.         /**
  65.         * Even the ordering by 'empId' (previously done using Comparable) can be implemented using 'Comparator';
  66.         * by thefollowing class
  67.         *<code>
  68.         *     class IdComparator implements Comparator<Employee>{
  69.         *          public int compare(Employee o1, Employee o2) {
  70.         *              return o1.getEmpId() - o2.getEmpId();
  71.         *          }
  72.         *     }
  73.         * </code>
  74.         *
  75.         * and then
  76.         *
  77.         * Collections.sort(employeeList, new IdComparator());
  78.         */
  79.     }
  80.    
  81.     private static List<Employee> createEmployeesAndAddThemToAList() {
  82.         return Arrays.asList(
  83.         new Employee(5, "Frank", 28),
  84.         new Employee(1, "Jorge", 19),
  85.         new Employee(6, "Bill", 34),
  86.         new Employee(3, "Michel", 10),
  87.         new Employee(7, "Simpson", 8),
  88.         new Employee(4, "Clerk", 16),
  89.         new Employee(8, "Lee", 40),
  90.         new Employee(2, "Mark", 30));
  91.     }
  92. }
  93.  
  94.  
  95. class Employee implements Comparable<Employee> {
  96.     protected int empId;
  97.     protected String name;
  98.     protected int age;
  99.    
  100.     /**
  101.     * @param empId Employee Id
  102.     * @param name  Employee Name
  103.     * @param age   Employee Age
  104.     */
  105.     public Employee(int empId, String name, int age) {
  106.         this.empId = empId;
  107.         this.name = name;
  108.         this.age = age;
  109.     }
  110.    
  111.     @Override
  112.     public String toString() {
  113.         return "Employee{" +
  114.             "empId=" + empId +
  115.             ", name='" + name + '\'' +
  116.             ", age=" + age +
  117.         '}';
  118.     }
  119.    
  120.     /**
  121.     * Sorting in natural ordering
  122.     *
  123.     * @param employee an Employee instance
  124.     * @return compared value
  125.     */
  126.     @Override
  127.     public int compareTo(@NotNull Employee employee) {
  128.         return this.empId - employee.empId;
  129.     }
  130.     /* Accesors and mutators */
  131. }
  132.  
  133. @SuppressWarnings("unused")
  134. class AgeComparator implements Comparator<Employee> {
  135.     @Override
  136.     public int compare(Employee employee1, Employee employee2) {
  137.         return employee1.age < employee2.age ? -1 : employee1.age == employee2.age ? 0 : 1;
  138.     }
  139. }
Add Comment
Please, Sign In to add comment