I am beginner in lambdas and trying to understand how it works. So I have this list of Student with id and score attributes and I have to sort it accoding to the score . My Code
import java.util.*;
class Student {
int id, score;
public Student(int id, int score) {
this.id = id;
this.score = score;
}
public String toString() {
return this.id + " " + this.score;
}
}
interface StudentFactory < S extends Student > {
S create(int id, int score);
}
class Test {
public static void main(String[] ad) {
StudentFactory < Student > studentFactory = Student::new;
Student person1 = studentFactory.create(1, 45);
Student person2 = studentFactory.create(2, 5);
Student person3 = studentFactory.create(3, 23);
List < Student > personList = Arrays.asList(person1, person2, person3);
// error in the below line
Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score));
System.out.println(personList);
}
}
as you can see I tried Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score));
it gave me error int cannot be dereferenced
I know the error expected I just want to show what I wanted.
So is there any way to sort the Student object accoding to score using lambdas only?
I have also seen similar post where I found that List.sort
or BeanComparator
is the other option but is there any way I can do it with lambdas?
Thanks