import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* {@link <a href=
* "https://[Log in to view URL]"
* target= "_blank">interfaccia funzionale Comparator<T></a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
public static class Student
{
private int id;
private String name, address;
public Student( int id, String name, String address )
{
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString()
{
return this.id + " " + this.name + " " + this.address;
}
}
/**
* @see Comparator
*
*/
public static class SortById implements Comparator<Student>
{
// 0: a = b
// -1: a < b
// +1: a > b
public int compare( Student a, Student b ) { return a.id - b.id; }
}
/**
* @see List
* @see ArrayList
* @see Collections#sort(List, Comparator)
*/
public static void main(String args[]) throws Exception {
// Unit test - interfaccia funzionale Comparator<T>
List<Student> archive = new ArrayList<Student>();
archive.add( new Student(111, "Pippo", "Treviglio, Via Giovanni Verga N21, Italia"));
archive.add( new Student(131, "Pluto", "Milano, Via Tito Livio N1, Italia"));
archive.add( new Student(121, "Paperino", "Genova, Via Marco Polo N53, Italia"));
archive.add( new Student(101, "Minni", "Roma, Via Misano N3, Italia"));
for( Student student : archive )
System.out.println( student );
Collections.sort( archive, new SortById() );
for( Student student : archive )
System.out.println( "-- " + student );
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: