Java 仅使用带有lambdas的Collection.Sort()对对象列表进行排序
我是lambdas的初学者,并试图了解它是如何工作的。因此,我有一个带有id和分数属性的学生列表,我必须根据分数对其进行排序。我的代码Java 仅使用带有lambdas的Collection.Sort()对对象列表进行排序,java,sorting,lambda,java-8,comparable,Java,Sorting,Lambda,Java 8,Comparable,我是lambdas的初学者,并试图了解它是如何工作的。因此,我有一个带有id和分数属性的学生列表,我必须根据分数对其进行排序。我的代码 import java.util.*; class Student { int id, score; public Student(int id, int score) { this.id = id; this.score = score; } public String toString()
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);
}
}
import java.util.*;
班级学生{
int-id,分数;
公立学生(国际id,国际分数){
this.id=id;
这个分数=分数;
}
公共字符串toString(){
返回this.id+“”+this.score;
}
}
界面StudentFactory{
S创建(int-id,int-score);
}
课堂测试{
公共静态void main(字符串[]ad){
StudentFactoryStudentFactory=Student::new;
Student person1=studentFactory.create(1,45);
Student person2=studentFactory.create(2,5);
Student person3=studentFactory.create(3,23);
ListpersonList=Arrays.asList(person1、person2、person3);
//下一行有错误
Collections.sort(personList,(a,b)->(a.score).compareTo(b.score));
System.out.println(personList);
}
}
如您所见,我尝试了Collections.sort(personList,(a,b)->(a.score.compareTo(b.score))
它给了我错误int不能被取消引用
我知道预期的错误,我只想显示我想要的。那么,有没有办法仅使用lambdas根据分数对学生对象进行排序?
我也看到过类似的帖子,我发现,
List.sort
或BeanComparator
是另一个选项,但有没有办法用lambdas实现它?谢谢 会有用的
int
不是一个对象,它是一个原语,您不能调用int.compareTo
,也不能调用int
上的任何其他方法
甚至比这更好
Comparator.comparingInt(s -> s.score)
或者,用一个getter
Comparator.comparingInt(Student::getScore)
使用
List.sort
对于是否使用lambdas或其他任何东西都没有影响。您只需编写personList.sort(Comparator.comparingit(s->s.score))
而不是Collections.sort(personList,Comparator.comparingit(s->s.score))
谢谢您的回复,但是我如何通过调用反向()
在比较器上。它在Collections.sort(personList,Comparator.comparingit(s->s.score).reversed()上给出了错误代码>说找不到符号s.score
您可能需要改为写(学生s)->s.score
。
Comparator.comparingInt(Student::getScore)