How to sort ArrayList using Comparator? [duplicate]

北城余情 提交于 2019-11-27 14:25:42

Use the Collections.sort(List, Comparator) method:

Collections.sort(students, Student.getCompByName());

Also in your code it would be good to use the List interface when declaring the List:

List<Student> students = new ArrayList();

You could also tighten up the code by using a Student[] and passing it to the ArrayList constructor:

public static void main(String[] args) {
    Student[] studentArr = new Student[]{new Student("Mike"),new Student("Hector"), new Student("Reggie"),new Student("zark")};
    List<Student> students = new ArrayList<Student>(Arrays.asList(studentArr));
    Collections.sort(students, Student.getCompByName());

    for(Student student:students){
        System.out.println(student.getName());
    }
}

Here is a Gist of the full source.

Use Collections.sort():

Collections.sort(students, getCompByName());

Note: might be useful to make your comparator a private static final variable.

Note 2: modifies the list in place; does not create a new list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!