gpt4 book ai didi

java - 仅使用带有 lambda 的 Collection.sort() 对对象列表进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:47 27 4
gpt4 key购买 nike

我是 lambdas 的初学者,正在尝试了解它的工作原理。所以我有这个带有 id 和 score 属性的 Student 列表,我必须根据 score 对它进行排序。我的代码

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);
}
}

如您所见,我尝试了 Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score)); 它给了我错误 int 不能被取消引用 我知道预期的错误我只是想展示我想要的。
那么有什么方法可以仅使用 lambda 来根据分数对 Student 对象进行排序吗?
我也看过类似的帖子,其中我发现 List.sortBeanComparator 是另一个选项,但是有什么方法可以用 lambda 来实现吗?
谢谢

最佳答案

(a, b) -> Integer.compare(a.score, b.score)

会起作用。 int 不是对象,它是原始类型,您不能调用 int.compareToint 上的任何其他方法。

比那更好

Comparator.comparingInt(s -> s.score)

或者,使用 setter/getter ,

Comparator.comparingInt(Student::getScore)

并且使用 List.sort 不会对您是否使用 lambda 或其他任何东西产生影响。你只需编写 personList.sort(Comparator.comparingInt(s -> s.score)) 而不是 Collections.sort(personList, Comparator.comparingInt(s -> s.score)).

关于java - 仅使用带有 lambda 的 Collection.sort() 对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com