Sort Elements using Comparable interface and Comparator interface

Sort Elements using Comparable interface and Comparator interface

There are two way to sort elements in a Collection:

  • using Comparable interface
  • using Comparator interface

1.Comparable interface exist on java.lang package while Comparator interface exist on java.util package.

2.Comparable interface has one method that name is compareTo() which is single parameterized while Comparator interface has also single method that name is compare() which is double parameterized.

3.When you want to fixed type of sorting you always prefer Comparable interface while if you want to dynamic type of sorting then we always prefer Comparator interface.

4.For example:Contact app is based on comparable while shopping site sorting is based on comparator.

Example of Comparable Interface:

Student.java


    public class Student implements Comparable<Student> {
        private int roll;
        private String name;
        private float marks;
        private String address;
       
        public int getRoll() {
        return roll;
        }
       
        public void setRoll(int roll) {
        this.roll = roll;
        }
       
        public String getName() {
        return name;
        }
       
        public void setName(String name) {
        this.name = name;
        }
       
        public float getMarks() {
        return marks;
        }
       
        public void setMarks(float marks) {
        this.marks = marks;
        }
       
        public String getAddress() {
        return address;
        }
       
        public void setAddress(String address) {
        this.address = address;
        }
       
        @Override
        public int compareTo(Student o) {
        return name.compareToIgnoreCase(o.getName());
        }
       
       }
              

First.java


    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    
    public class First {
     public static void main(String[] args) {
    
     ArrayList<Student> students = new ArrayList();
     // create connection
     try {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "root");
     PreparedStatement ps = con.prepareStatement("select * from student");
     ResultSet rs = ps.executeQuery();
     while (rs.next()) {
    
     Student s = new Student();
     s.setRoll(rs.getInt(1));
     s.setName(rs.getString(2));
     s.setMarks(rs.getFloat(3));
     s.setAddress(rs.getString(4));
     // add student into collection
     students.add(s);
    
     }
    
     } catch (Exception e) {
     System.out.println(e);
     }
    
     // sort these collection
     Collections.sort(students);
    
     Iterator<Student> it = students.iterator(); 
     while (it.hasNext()) {
     Student std = it.next();
     System.out.println(std.getRoll() + "\t" + std.getName() + "\t" + std.getMarks() + "\t" + std.getAddress());
     }
    
     }
    }

Table information:

mysql> select * from student;

+------+--------------+-------+-------------+
| roll | name         | marks | address     |
+------+--------------+-------+-------------+
|    1 | deep singh   |  67.7 | gzb         |
|    2 | somesh singh |  79.7 | gzb         |
|    3 | salim khan   |  68.7 | delhi       | 

Output :

1 deep singh   67.7 gzb
3 salim khan   68.7 delhi
2 somesh singh 79.7 gzb
Example of Comparator Interface:

Student.java


    public class Student {
        private int roll;
        private String name;
        private float marks;
        private String address;
       
        public int getRoll() {
        return roll;
        }
       
        public void setRoll(int roll) {
        this.roll = roll;
        }
       
        public String getName() {
        return name;
        }
       
        public void setName(String name) {
        this.name = name;
        }
       
        public float getMarks() {
        return marks;
        }
       
        public void setMarks(float marks) {
        this.marks = marks;
        }
       
        public String getAddress() {
        return address;
        }
       
        public void setAddress(String address) {
        this.address = address;
        }
       }

NameBasedSorting.java


    import java.util.Comparator;

    public class NameBasedSorting implements Comparator<Student> {
    
     @Override
     public int compare(Student o1, Student o2) {
     return o1.getName().compareTo(o2.getName());
     }
    
    }

First.java


    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    
    public class First {
     public static void main(String[] args) {
    
     ArrayList<Student> students = new ArrayList();
     // create connection
     try {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con =    DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root",         "root");
     PreparedStatement ps = con.prepareStatement("select * from student");
     ResultSet rs = ps.executeQuery();
     while (rs.next()) {
    
     Student s = new Student();
     s.setRoll(rs.getInt(1));
     s.setName(rs.getString(2));
     s.setMarks(rs.getFloat(3));
     s.setAddress(rs.getString(4));
     // add student into collection
     students.add(s);
    
     }
    
     } catch (Exception e) {
     System.out.println(e);
     }
    
     // sort these collection
     Collections.sort(students, new NameBasedSorting()); 
    
     Iterator<Student> it = students.iterator(); 
     while (it.hasNext()) {
     Student std = it.next();
     System.out.println(std.getRoll() + "\t" + 
        std.getName() + "\t" + std.getMarks() + "\t" + std.getAddress());
     }
    
     }
    
    }    

Output is:

1 deep singh    67.7  gzb
3 salim khan    68.7  delhi
2 somesh singh  79.7  gzb

You can also replace your NameBasedSorting with Annonymous inner class:

// sort these collection
 Collections.sort(students, new Comparator<Student>() {

 @Override
 public int compare(Student o1, Student o2) {

 return o1.getName().compareTo(o2.getName());
 }
});

You can also replace your annonymous inner class with lambda expression:

// sort these collection using lambda expression
Collections.sort(students,(x,y)->x.getName().compareTo(y.getName()));

No comments: