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));
>! }
I konw that I need to send the object and the method to this method, But I am confused why I can't just send the Object and method as normal parameters like Comparator.comparingInt(Student, student.get age())) (I konw it doesn't work but if I don't use Lambda expression or method reference I need to create a class in this or what?)
what I do like this is failed:
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();
like this, I konw the the former version of the simpify version,but I can't understand how the usage and change of comparingInt sorts of. My understanding about this is that I thought they also have the Lambda in their method body,so what outside need to do is just transfer the parameter about the object and method. But why in this way? I am curious whether there is some theory or just some rules I need to remember?
My description may be not very clearly,Thank you for answering my question!
You can't do anything like what you're trying to do. The closest thing is to not use comparingInt
and just write (c1, c2) -> Integer.compare(c1.getAge(), c2.getAge())
.
comparingInt
just takes a function to run on its arguments. It does not, and cannot, take the arguments itself -- not directly, at least; you could of course write
Comparator<Student> comparator = comparingInt(Student::getAge);
comparator.compare(s1, s2);