public static void main(String[] args) {
Student[] students = new Student[4];
students[0] = new Student("guy1", 103, 334); // height / age (randomly written)
students[1] = new Student("guy2", 87, 534);
students[2] = new Student("guy3", 103, 232);
students[3] = new Student("guy4", 110, 121);
Arrays.sort(students, Comparator.comparingInt(Student::getAge)); // method reference
Arrays.sort(students, Comparator.comparingInt(student -> student.getAge())); // Lambda expression
// the source code of the comparingInt method
>! public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
>! Objects.requireNonNull(keyExtractor);
>! return (Comparator<T> & Serializable)
>! (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
>! }
我知道我需要将对象和方法发送到此方法,但我很困惑为什么我不能将对象和方法作为普通参数发送,例如 Comparator.comparingInt(Student, Student.getage())) (我知道它不起作用,但如果我不使用 Lambda 表达式或方法引用,我需要在其中创建一个类或什么?)
我这样做是失败的:
Arrays.sort(students, Comparator.comparingInt(students,c1,getAge) kinds of , actually all can't pass IDEA.
// Animal a = new Animal() { former version
// @Override
// public void run() {
// System.out.println("dog runs");
// }
// };
// Animal a = () -> {
// System.out.println("dog runs");
// };
//
// a.run();
这样,我知道了简化版本的前一个版本,但是我不明白compareInt的用法和变化是怎样的。我对此的理解是,我认为他们的方法体中也有 Lambda,所以外部需要做的只是传递有关对象和方法的参数。但为什么要这样呢?我很好奇是否需要记住一些理论或只是一些规则?
我的描述可能不是很清楚,谢谢您回答我的问题!
你无法做任何你想做的事。最接近的是不使用
comparingInt
而只写(c1, c2) -> Integer.compare(c1.getAge(), c2.getAge())
。
comparingInt
just 接受一个函数来运行它的参数。它本身不会也不可能接受论点——至少不能直接接受;你当然可以写
Comparator<Student> comparator = comparingInt(Student::getAge);
comparator.compare(s1, s2);