用Java排序LinkedList

时间:2018-08-07 04:53:02

标签: java sorting linked-list

我有一个列表:

 LinkedList<Student> student = new LinkedList<Student>();

在Student类中,它具有属性字符串名称。我想按名称对学生名单进行排序。 有什么办法可以做到吗?

5 个答案:

答案 0 :(得分:2)

student.sort(Comparator.comparing(Student::getName));

详细了解comparators

答案 1 :(得分:1)

您可以定义一个比较器来执行此操作。一种简单的方法是使用匿名类。 https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

Collections.sort(student, new Comparator<Student>() {
    public int compare(Student a, Student b) {
        return a.getName().compare(b.getName());
    }
};

答案 2 :(得分:0)

您可以使用Collections.sort方法接受comparator作为其第二个参数。传入定义您想要的顺序的comparator。例如,给定Student类,则可以将Collections.sort与自定义comparator结合使用,以按如下所示的名称升序对Student进行排序:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

class Student {

    private final String name;
    private final int score;

    Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", score=" + score + "]";
    }

    public static void main(String[] args) {
        List<Student> list = new LinkedList<>(
                Arrays.asList(new Student("David", 3), new Student("Alice", 3), new Student("Thomas", 9)));

        System.out.println("Before Sort: " + list);

        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        System.out.println("After Sort: " + list);
    }

}

这将产生输出

before: [Student [name=David, score=3], Student [name=Alice, score=3], Student [name=Thomas, score=9]]
after: [Student [name=Alice, score=3], Student [name=David, score=3], Student [name=Thomas, score=9]]

答案 3 :(得分:0)

如果您使用的是Java> 8,则可以使用 Lambda表达式,并且您将得到如下内容:

Collections.sort(student, (p1, p2) -> p1.name.compareTo(p2.name));

或在列表中使用排序方法

student.sort((p1, p2) -> p1.name.compareTo(p2.name));

答案 4 :(得分:0)

您可以使用此

   student.sort(Comparator.comparing(Student:: getName));//Single Sorting
    student.sort(Comparator.comparing(Student:: getName).reversed());//Single reverse Sorting
    student.sort(Comparator.comparing(Student:: getName).thenComparing(Student::getScore));//Double