Comparateur en Java
Interface de comparateur
L'interface Java Comparator est utilisée pour comparer deux objets de mêmes classes sur la base d'un critère qui compare par roll no. ou nom etc.
Nous pouvons trier les éléments d'une ArrayList en utilisant la fonction de tri, mais lorsqu'il s'agit de trier les éléments en fonction des membres de données, la fonction de tri n'est pas un bon choix car vous devrez réécrire le code de tri pour différents critères.
En utilisant l'interface Comparator, nous pouvons facilement ordonner les objets de la classe définie par l'utilisateur. L'interface de comparaison est présente dans le package java.util La classe de comparaison a deux méthodes :
Nous pouvons trier les éléments d'une ArrayList en utilisant la fonction de tri, mais lorsqu'il s'agit de trier les éléments en fonction des membres de données, la fonction de tri n'est pas un bon choix car vous devrez réécrire le code de tri pour différents critères.
En utilisant l'interface Comparator, nous pouvons facilement ordonner les objets de la classe définie par l'utilisateur. L'interface de comparaison est présente dans le package java.util La classe de comparaison a deux méthodes :
- Comparer (Object1, Object2) compare le premier objet avec le second
- est égal à (élément objet)
Ici, nous utiliserons la classe Collection qui fournit la méthode sort() pour trier les éléments de la liste en utilisant le comparateur donné.
Syntaxe :
public void sort(List list , Comparator C)
Voyons comment fonctionne le comparateur à l'aide de ce court exemple.
Ici, nous avons cinq classes :
- Classe Employé (qui définit les données membres de la classe)
- Classe IdComparator implémentant l'interface Comparator (cela compare les objets à l'aide du membre de données Id)
- Classe SalaryComparator implémentant l'interface Comparator (cela compare les objets à l'aide du membre de données Salary)
- Classe NameComparator implémentant l'interface Comparator (cela compare les objets à l'aide du membre de données Name)
- Classe principale ExComparator<
Code
package logicProgramming; import java.util.ArrayList; // importing array list import java.util.Collections; //importing collections import java.util.Comparator; //importing Comparator //a class to represent employee, //this class defines all the data members for employee class Employee { public int id; public String name; public long salary; //Constructor public Employee(int id,String name,long salary) { this.id=id; this.name=name; this.salary=salary; } } //this class is a comparator class which will //compare two employee objects based on employee id class IdComparator implements Comparator<Employee> { public int compare(Employee E1,Employee E2) { // if Id's are same that is objects are equal it will return 0 if(E1.id==E2.id) {return 0;} // if id of first object is greater than second object than it will return 1 else if(E1.id>E2.id) {return 1;} // if id of first object is less than second object than it will return -1 else {return -1;} } } //This class is used to compare the employee objects by salary class SalaryComparator implements Comparator<Employee> { public int compare(Employee E1,Employee E2) { // if salary of both object is same it will return 0 if(E1.salary==E2.salary) {return 0;} // if salary of first object is greater than second object than it will return 1 else if(E1.salary>E2.salary) {return 1;} // if salary of first object is less than second object than it will return -1 else {return -1;} } } //this class is a comparator class which will //compare two employee objects based on name //and will sort the employees alphabatically class NameComparator implements Comparator<Employee> { public int compare(Employee E1,Employee E2) { return(E1.name.compareTo(E2.name)); } } //main class public class ExComparator { public static void main(String arg[]) { ArrayList<Employee> list=new ArrayList<Employee>();//array list to hold the employee objects Employee E1=new Employee(100,"Muskan Singh",30885); Employee E2=new Employee(200,"Amitabh Singh",29000); Employee E3=new Employee(300,"O.P. Rai",29500); list.add(E1); //adding employee objects list.add(E2); list.add(E3); System.out.println("\n\n\nSorting By Name............"); Collections.sort(list, new NameComparator()); // sorting the objects of the list by name //looping through the list to print objects for(Employee E:list) { System.out.println("Name :"+E.name+"\nId :"+E.id+"\nSalary :"+E.salary);//printing the sorted objects to the screen System.out.println(); } System.out.println("\n\n\nSorting By Salary............"); Collections.sort(list, new SalaryComparator()); // sorting the objects of the list by salary. for(Employee E:list) { System.out.println("\nSalary :"+E.salary+"\nName :"+E.name+"\nId :"+E.id); System.out.println(); } System.out.println("\n\n\nSorting By Id............"); Collections.sort(list, new IdComparator());// sorting the objects of the list by Id. //looping through the list to print objects for(Employee E:list) { System.out.println("Id :"+E.id+"\nName :"+E.name+"\nSalary :"+E.salary); System.out.println(); }//printing the sorted objects to the screen } }
Sortie
Sorting By Name............ Name :Amitabh Singh Id :200 Salary :29000 Name :Muskan Singh Id :100 Salary :30885 Name :O.P. Rai Id :300 Salary :29500 Sorting By Salary............ Salary :29000 Name :Amitabh Singh Id :200 Salary :29500 Name :O.P. Rai Id :300 Salary :30885 Name :Muskan Singh Id :100 Sorting By Id............ Id :100 Name :Muskan Singh Salary :30885 Id :200 Name :Amitabh Singh Salary :29000 Id :300 Name :O.P. Rai Salary :29500