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 " Name = " + name + " "+
" Percentage = " + percentage +" " ;
}
}

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 : " + list ) ;

Collections.sort( list , new CompareWithPercentage( ) ) ;

System.out.println(" After Sorting : " + list ) ;
}
}

 


For more of such hot topics read my other posts here :

Visit my new website



Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 311 0

Please login to comment on this post.
There are no comments yet.
What Is Difference Between Equals() Method And == Operator In Java ?
First Man On The Moon , Neil Armstrong Dies At Age 82