仅使用具有lambdas的Collection.sort()对对象列表进行排序

sin*_*ash 3 java sorting lambda comparable java-8

我是lambda的初学者,并试图了解它是如何工作的.所以我有这个具有id和分数属性的学生列表,我必须根据分数对其进行排序.我的守则

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我试过Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score));它给了我错误int cannot be dereferenced我知道错误预期我只想展示我想要的东西.
那么有没有办法只使用lambdas对Student对象进行排序?
我也看过类似的帖子,我发现List.sort或者BeanComparator是另一种选择但是有什么方法可以用lambdas做到吗?
谢谢

Lou*_*man 10

(a, b) -> Integer.compare(a.score, b.score)
Run Code Online (Sandbox Code Playgroud)

会工作. int不是一个对象,它是一个原始的,你不能调用int.compareTo,或任何其他方法int.

甚至比那更好

Comparator.comparingInt(s -> s.score)
Run Code Online (Sandbox Code Playgroud)

或者,用吸气剂,

Comparator.comparingInt(Student::getScore)
Run Code Online (Sandbox Code Playgroud)

使用List.sort并不会影响你是否使用lambdas或其他什么.你只是写personList.sort(Comparator.comparingInt(s -> s.score))而不是Collections.sort(personList, Comparator.comparingInt(s -> s.score)).

  • 你可能需要编写`(Student s) - > s.score`. (2认同)