Forum Stats

  • 3,837,378 Users
  • 2,262,252 Discussions
  • 7,900,266 Comments

Discussions

How to override compare method in Comparator

user575089
user575089 Member Posts: 466
edited Jul 13, 2018 12:24PM in Java Programming

I'm stuck to override compare method in Comparator  for ascending order sorting.

I want to sort in ascending order of  roll number

Code:

class Sortbyroll implements Comparator<Student>

{

    public int compare(Student a, Student b)

    { 

      

  if (a.rollno > b.rollno  ){

   return 1;

  }

    if (a.rollno < b.rollno){

   return -1;

  }

  if (a.rollno == b.rollno){

   return 0;

  }

}

what to do if I want to sort in ascending order ?

Best Answer

  • rpc1
    rpc1 Member Posts: 1,503
    edited Jul 13, 2018 7:31AM Answer ✓
    Does collection sort use this sort  algorithm which you mentioned ?

    Surely not, buble sort uses for education only, because it most simple.

    Collections.sort - algorithm depends of java version and sorted object, as usual it is a merge sort,

    Collections is an open library you can view it sources in JDK

«1

Answers

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Jul 11, 2018 2:44AM

    You may want to post your Student src as well.

  • user575089
    user575089 Member Posts: 466
    edited Jul 11, 2018 6:18AM

    class Student{

        int rollno;

        int getRollno(){

            return rollno;

        }

        public Student(int rollno){

            this.rollno=rollno;

        }

        void setRollno(int rollno){

            this.rollno=rollno;

        }

    }

  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Jul 11, 2018 7:11AM

    Slightly modified your Student for the demo purposes.

    public class Student{   private String name = null;   private int rollno = -1;   public Student(String name, int no)   {      this.name = name;      this.rollno = no;   }   public int getRollno()   {      return rollno;   }   public void print()   {      System.out.println(name + " - " + rollno);   }}

    And, wherever it is needed to be tested you could do something like below. I have used a test class for the demo.

    public class StudentSortTest{   public static void main(String[] args)   {      Student s1 = new Student("C", 10);      Student s2 = new Student("D", 20);      Student s3 = new Student("A", 30);            java.util.ArrayList<Student> al = new java.util.ArrayList<Student>();      al.add(s3);      al.add(s1);      al.add(s2);            System.out.println("\n Ascending ");            al.sort(new Sortbyroll());            for (Student s : al)      {         s.print();      }            System.out.println("\n Descending ");            al.sort(new Sortbyroll().reversed());            for (Student s : al)      {         s.print();      }         }}
  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Jul 11, 2018 7:59AM

    Here is the slightly modified comparator :

    public class Sortbyroll implements java.util.Comparator<Student>{   @Override   public int compare(Student a, Student b)   {      int iRetVal = a.getRollno() == b.getRollno()                     ? 0                     : a.getRollno() < b.getRollno() ? -1 : 1;      return iRetVal;   }}
  • Unknown
    edited Jul 11, 2018 12:52PM
    I'm stuck to override compare method in Comparator for ascending order sorting.

    Well - you can't just say you are 'stuck'.

    You actually have to tell us WHAT you are stuck on?

    Have you READ the Oracle docs for the Comparator interface?

    https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

    Is there something in the API doc for the 'compare' method you don't understand?

    what to do if I want to sort in ascending order ?

    You return the required values shown in the API doc above that indicate the proper ordering of your objects.

    Is there some reason you are using Comparator instead of Comparable?

    I suggest you read the trails in The Java Tutorials about 'Object Ordering'

    https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

    Read them. Try the examples. Modify the examples to fit your own use case.

  • user575089
    user575089 Member Posts: 466
    edited Jul 13, 2018 4:02AM
    rp0428 wrote:I'm stuck to override compare method in Comparator for ascending order sorting.Well - you can't just say you are 'stuck'.You actually have to tell us WHAT you are stuck on?

    Okay .  I'm stuck to understand how this is connected to Ascending sorting ? This is just a comparison below.

    class Sortbyroll implements Comparator<Student>{public int compare(Student a, Student b)  {if (a.rollno > b.rollno  ){return 1;  }  if (a.rollno < b.rollno){return -1;  }  if (a.rollno == b.rollno){return 0;  }}

    And here  we are sorting

    Collection.sort(students, new Sortbyroll() )

    But how this is sorting  by "Ascending"  ?  where we are instructing to sort by Ascending ? We have not yet instructed to sort by "Ascending" or "Descending" ...Is not it ?  I could not figure out how this would sort by Ascending but  not by Descending .   I'm stuck right at this spot.

  • rpc1
    rpc1 Member Posts: 1,503
    edited Jul 13, 2018 4:30AM

    <strong><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29">sort</a></strong>(<a href="https://docs.oracle.com/javase/7/docs/api/java/util/List.html" title="interface in java.util">List</a><T> list) - Sorts the specified list into ascending order, according to the natural ordering of its elements.

    If you need other order you have to define comparator

    <strong><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29">sort</a></strong>(<a href="https://docs.oracle.com/javase/7/docs/api/java/util/List.html" title="interface in java.util">List</a><T> list, <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html" title="interface in java.util">Comparator</a><? super T> c)  Sorts the specified list according to the order induced by the specified comparator.

    In your example you can change order in comparator - this is descending

      if (a.rollno > b.rollno  ){ 

            return -1

        } 

     

         if (a.rollno < b.rollno){ 

            return 1

        }

  • user575089
    user575089 Member Posts: 466
    edited Jul 13, 2018 5:41AM
    rpc1 wrote:In your example you can change order in comparator - this is descending  if (a.rollno > b.rollno ){  return  -1;  }  if (a.rollno < b.rollno){  return 1;  } 

    Could you please explain the following.

    Why  this descending ?

    if (a.rollno > b.rollno ){return -1;}if (a.rollno < b.rollno){return 1;}

    Or

    why  this is ascending

    { if (a.rollno > b.rollno  ){ return 1;   }   if (a.rollno < b.rollno){ return -1;   } 
  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Jul 13, 2018 5:43AM

    If you debug with the JDK src included available, you will be able to step through the algorithm that will explain what you are looking for.

  • rpc1
    rpc1 Member Posts: 1,503
    edited Jul 13, 2018 6:01AM
    user575089 wrote:
    Could you please explain the following.Why this descending ?if (a.rollno > b.rollno ){ return -1; }  if (a.rollno < b.rollno){ return 1; }
    Orwhy this is ascending 

    {  if (a.rollno > b.rollno ){  return 1;   }     if (a.rollno < b.rollno){  return -1;   } 

    At first you need to understand how sorting algorithm (start from buble sort https://www.javatpoint.com/bubble-sort-in-java

    For example you have the list with students rollno

    list = (3,1)

    you comparator have to compare elements with each other.

    iteration

    res = compare(3,1);

       if (r==1 )  // element 3  greater then 1

          replace(list,1,2);

    out list : (1,3)

    This is ascending order, because you comparator guess that 3>1

    Whe you comparator is descending

    compare(3,1) returns -1 therefore list will not be changed, because it guess that 3<1

This discussion has been closed.