Sunday, August 27, 2017

Compare Objects using Comparator

Compare Students based on there score. If score is equal , then sort those students based on there name.

import java.util.Arrays;
import java.util.Comparator;

class Student {
   String name;
   int score;
   public Student(String name, int score) {
      super();
      this.name = name;
      this.score = score;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getScore() {
      return score;
   }
   public void setScore(int score) {
      this.score = score;
   }
}

public class SortStudents implements Comparator<Student> {
   public static void main(String[] args) {
      Student[] students = new Student[5];
      students[0] = new Student("Paras", 100);
      students[1] = new Student("Varun", 200);
      students[2] = new Student("Rahul", 300);
      students[3] = new Student("Parul", 400);
      students[4] = new Student("Shubham", 100);
      Arrays.sort(students, new SortStudents());
      printArray(students);
   }
  
   static void printArray(Student[] students){
      for(Student s: students){
         System.out.println("Name: "+ s.getName()
         +" Score: "+ s.getScore());
      }
   }
  
   /*Sort students based on score and if score equals
    *then sort using names
    **/
   public int compare(Student s1, Student s2) {
      if(s1.getScore()==s2.getScore())
         return s2.getName().compareTo(s1.getName());
      else
         return s2.getScore()-s1.getScore();
   }
}

Output
Name: Parul   Score: 400
Name: Rahul   Score: 300
Name: Varun   Score: 200
Name: Shubham Score: 100
Name: Paras   Score: 100

No comments:

Post a Comment