1.

How can you use Comparable and Comparator interfaces to sort collections?

Answer»

Comparable is part of java.lang package, which is used to compare another object from itself, the way it works that the class needs to implement the comparable interface and need to override the compare method which takes another object as a parameter, this scenario is when we use it to implement natural comparison with another object, it could be any user-defined class.The return type of compareTo() method is int type which could return three different values (-1, 0, 1) Below is the code snippet for same.

/* This class implements the Comparable interface which uses as a comparison between two objects. *   Class has override the compareTo() method */ class StudentComparableDemo implements Comparable<StudentComparableDemo>{   int rollno;   String name;   int age;   StudentComparableDemo(int rollno,String name,int age){   this.rollno=rollno;   this.name=name;   this.age=age;   }   //This method performs the comparison of object of Student using the attribute the age which COMPARES with the age of other student object. public int compareTo(StudentComparableDemo ST){   if(age==st.age)   // If age of both the object is same it will return 0 return 0;   else if(age>st.age)   return 1;   else   return -1;   }   }  

The comparator is an interface of java.util package which predominantly works on collection library, the best use case is to compare the two different collection object. The sorting can perform using Collections utility class.

Below is the code representation.

import java.util.*; import java.lang.*; import java.io.*; // This class to represent an Employee domain object which eventually works store the employee domain information. class Employee {    int empid;    String name, address;    // CONSTRUCTOR    public Employee(int empid, String name,                               String address)    {        this.empid = empid;        this.name = name;        this.address = address;    }    // Used to print Employee details in main()    public String toString()    {        return this.empid + " " + this.name +                           " " + this.address;    } } /* This classes responsible for performing the compare and sorting the employee result according to the empid */ class SortbyId implements CompemployeeListator<Employee> {    // Used for sorting in ascending order of    // roll number    public int compemployeeListe(Employee a, Employee b)    {        return a.empid - b.empid;    } } /* This classes responsible to performs the compare and sorting the employee result according to the empid */   class Sortbyname implements CompemployeeListator<Employee> {    // Used for sorting in ascending order of    // roll name    public int compemployeeListe(Employee a, Employee b)    {        return a.name.compemployeeListeTo(b.name);    } } // The Driver class perform the operation on sorting the employee object class Main {    public static void main (String[] employeeListgs)    {        employeeListrayList<Employee> employeeList = new employeeListrayList<Employee>();        employeeList.add(new Employee(111, "bbbb", "LONDON"));        employeeList.add(new Employee(131, "aaaa", "nyc"));        employeeList.add(new Employee(121, "cccc", "jaipur"));        System.out.println("Unsorted");        for (int i=0; i<employeeList.size(); i++)            System.out.println(employeeList.get(i));

Collections are the utility class which has the sort method takes an input of list of the employee and implemented comparator class use to perform the sorting.

       Collections.sort(employeeList, new SortbyId());        System.out.println("\nSorted by empid");        for (int i=0; i<employeeList.size(); i++)            System.out.println(employeeList.get(i));        Collections.sort(employeeList, new Sortbyname());        System.out.println("\nSorted by name");        for (int i=0; i<employeeList.size(); i++)            System.out.println(employeeList.get(i));    } }


Discussion

No Comment Found