public class test {
public static void main(String[] args) {
//存储person对象的列表
ArrayList<Person> personArrayList = new ArrayList<>();
personArrayList.add(new Person("文泽稳", 27, "男"));
personArrayList.add(new Person("王祺", 21, "女"));
personArrayList.add(new Person("文学才", 58, "男"));
personArrayList.add(new Person("彭亮容", 60, "女"));
personArrayList.add(new Person("文娟", 32, "女"));
personArrayList.add(new Person("文泽芳", 29, "女"));
//1.匿名内部内的方式
Collections.sort(personArrayList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o2.getAge() - o1.getAge();
}
});
System.out.println(personArrayList);
//2.lambda方式
Collections.sort(personArrayList, (person1, person2) -> {
return person2.getAge() - person1.getAge();
});
System.out.println(personArrayList);
//3.静态方法的引用
Collections.sort(personArrayList, Person::comparByAge);
System.out.println(personArrayList);
//4.实例方法的调用
PersonUtil person = new PersonUtil();
Collections.sort(personArrayList, person::compareByName);
System.out.println("文泽稳".hashCode());
System.out.println("王祺".hashCode());
System.out.println(personArrayList);
//5.构造函数方法的调用(依赖函数式接口)
IPerson iPerson = Person::new;
iPerson.intitPersom("马军", 31, "男");
System.out.println(person);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String userName;
private int age;
private String gendar;
public static int comparByAge(Person person1, Person person2) {
return person1.getAge() - person2.getAge();
}
@Override
public String toString() {
return "Person{" +
"userName='" + userName + '\'' +
", age=" + age +
", gendar='" + gendar + '\'' +
'}';
}
}
class PersonUtil {
public int compareByName(Person Person1, Person person2) {
return Person1.getUserName().hashCode() - person2.getUserName().hashCode();
}
}
interface IPerson {
Person intitPersom(String userName, int age, String gendar);
}