格式
(o1, o2) -> {
return o1.* > o2.* ? 0 : -1;
}
等同于
new Comparator<Student>() {
@Override
public int compare(o1, o2) {
return o1.* > o2.* ? 0 : 1;
}
}
示例
顺序取决于返回值
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @author rui
* @create 2020-06-28 17:38
*/
public class Mar {
public static void main(String[] args) {
List<Student> msgList = new ArrayList<>();
msgList.add(new Student(12, "小明"));
msgList.add(new Student(10, "小弘"));
msgList.add(new Student(14, "小大"));
msgList.add(new Student(9, "小是"));
msgList.sort((o1, o2) -> {
return o1.getAge() > o2.getAge() ? 0 : -1;
});
for (Student student : msgList
) {
System.out.println(student);
}
msgList.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() > o2.getAge() ? 0 : 1;
}
});
System.out.println("***********************");
for (Student student : msgList
) {
System.out.println(student);
}
}
}
class Student {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}