Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to implement Comparator Interface in Java with an example ?

Program to demonstrate the implementation of Comparator Interface in Java

package com.hubberspot.collections.example;

import java.util.*;

class Student 
{
  public String name; 
  public double percentage;
 
  Student(String name, double percentage)
  {
    this.name = name; this.percentage = percentage; 
  }
 
  public String toString()
  {
    return "\nName = " + name + "\n"+
           "Percentage = " + percentage+"\n";
  }
}

class CompareWithPercentage implements Comparator
{
  public int compare(Object obj1, Object obj2)
  {
    Student o1 = (Student)obj1;
    Student o2 = (Student)obj2;
  
    if(o1.percentage == o2.percentage)
       return 0;

    if(o1.percentage > o2.percentage)
       return 1;
    return -1;
  }
}

public class ComparatorExample
{
  public static void main(String[] args)
  {
    ArrayList list = new ArrayList();

    list.add(new Student("Dinesh",76.2));
    list.add(new Student("Jonty",96.5));
    list.add(new Student("Gunjan",81.7));
    list.add(new Student("Parishrut",62.1));
  
    System.out.println("Before Sorting : \n" + list);
  
    Collections.sort(list,new CompareWithPercentage());
  
    System.out.println("\nAfter Sorting : \n" + list);
  }
}

Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot