Étudions cette fois avec vous la référence de la méthode Java 8.
Tout d'abord, faisons une méthode d'épée d'âge par la méthode avant Java 8.
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//Classe anonyme
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
}
Résultat de la mise en œuvre: [Person (name = Mary, age = 23), Person (name = Jill, age = 24), Person (name = Jack, age = 25), Person (name = Lily, age = 27), Person (nom = Dock, âge = 34)]
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//Formule Lambda
Collections.sort(personList,(p1,p2) -> p1.getAge() - p2.getAge());
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
}
Résultat de la mise en œuvre: [Person (name = Mary, age = 23), Person (name = Jill, age = 24), Person (name = Jack, age = 25), Person (name = Lily, age = 27), Person (nom = Dock, âge = 34)]
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//référence de méthode statique
Collections.sort(personList, Person::CompareAge);
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
public static int CompareAge(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
}
Recommended Posts