Java 集合 ArrayList对象排序

在本教程中,我们将看到如何使用可比较对象和比较器接口按属性对对象的ArrayList进行排序。如果您正在寻找对StringInteger的简单ArrayList进行排序,那么您可以参考以下教程 –

我们通常使用Collections.sort()方法对一个简单的ArrayList进行排序。但是,如果ArrayList自定义对象类型,那么在这种情况下,您有两个选项可用于排序 – 可比较和比较器接口。在介绍它们的示例之前,让我们看看当我们尝试对对象的arraylist进行排序而不实现任何这些接口时的输出是什么。

为什么需要ComparableComparator

考虑下面的例子 – 我有一个 Student 类,它具有学生姓名,掷骰号和学生年龄等属性。

public class Student  {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
         this.rollno = rollno;
         this.studentname = studentname;
         this.studentage = studentage;
    }

    public String getStudentname() {
         return studentname;
    }
    public void setStudentname(String studentname) {
    this.studentname = studentname;
    }
    public int getRollno() {
    return rollno;
    }
    public void setRollno(int rollno) {
    this.rollno = rollno;
    }
    public int getStudentage() {
    return studentage;
    }
    public void setStudentage(int studentage) {
    this.studentage = studentage;
    }   
}

我想要一个学生对象的ArrayList。我们这样做 –

import java.util.*;
public class ArrayListSorting  {

     public static void main(String args[]){
       ArrayList<Student> arraylist = new ArrayList<Student>();
       arraylist.add(new Student(223, "Chaitanya", 26));
       arraylist.add(new Student(245, "Rahul", 24));
       arraylist.add(new Student(209, "Ajeet", 32));

       Collections.sort(arraylist);

       for(Student str: arraylist){
            System.out.println(str);
       }
     }
}

我试图在对象列表上调用Collections.sort()并繁荣!我得到了这样的错误信息 –
线程main中的异常java.lang.Error:未解决的编译问题:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type Student is not a valid substitute for the bounded parameter &gt; at beginnersbook.com.Details.main(Details.java:11)

原因:我刚刚在对象的ArrayList上调用了sort方法,除非我们使用ComparableComparator之类的接口,否则它实际上不起作用。

现在您必须了解这些接口的重要性。让我们看看如何使用它们以我们的方式完成排序。

使用Comparable排序ArrayList<Object>

假设我们需要对ArrayList<Student>进行排序。根据学生年龄属性。这是如何做到的 – 首先实现Comparable接口,然后覆盖compareTo方法。

package beginnersbook.com;

public class Student implements Comparable {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
    ...
    //getter and setter methods same as the above example 
    ...
    @Override
    public int compareTo(Student comparestu) {
        int compareage=((Student)comparestu).getStudentage();
        /* For Ascending order*/
        return this.studentage-compareage;

        /* For Descending order do like this */
        //return compareage-this.studentage;
    }

    @Override
    public String toString() {
        return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
    }

}

现在我们可以在ArrayList上调用Collections.sort

import java.util.*;
public class ArrayListSorting  {

    public static void main(String args[]){
       ArrayList<Student> arraylist = new ArrayList<Student>();
       arraylist.add(new Student(223, "Chaitanya", 26));
       arraylist.add(new Student(245, "Rahul", 24));
       arraylist.add(new Student(209, "Ajeet", 32));

       Collections.sort(arraylist);

       for(Student str: arraylist){
            System.out.println(str);
       }
    }
}

输出:

[ rollno=245, name=Rahul, age=24]
[ rollno=223, name=Chaitanya, age=26]
[ rollno=209, name=Ajeet, age=32]

Comparable做了我们的工作为什么我们需要Comparator了?

由于Comparable是由对象进行排序的同一个类实现的,所以它会绑定你的排序逻辑,在大多数情况下都可以,但是如果你想要的方法不仅仅是对类对象进行排序了应该使用比较器。

使用Comparator的多个属性对ArrayList<Object>进行排序

我们优先使用Comparatorcompare方法进行排序。

package beginnersbook.com;
import java.util.Comparator;
public class Student  {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
    ...
    //Getter and setter methods same as the above examples
    ...
    /*Comparator for sorting the list by Student Name*/
    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {

    public int compare(Student s1, Student s2) {
       String StudentName1 = s1.getStudentname().toUpperCase();
       String StudentName2 = s2.getStudentname().toUpperCase();

       //ascending order
       return StudentName1.compareTo(StudentName2);

       //descending order
       //return StudentName2.compareTo(StudentName1);
    }};

    /*Comparator for sorting the list by roll no*/
    public static Comparator<Student> StuRollno = new Comparator<Student>() {

    public int compare(Student s1, Student s2) {

       int rollno1 = s1.getRollno();
       int rollno2 = s2.getRollno();

       /*For ascending order*/
       return rollno1-rollno2;

       /*For descending order*/
       //rollno2-rollno1;
   }};
    @Override
    public String toString() {
        return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
    }

}

ArrayList类:

package beginnersbook.com;
import java.util.*;
public class Details  {

    public static void main(String args[]){
       ArrayList<Student> arraylist = new ArrayList<Student>();
       arraylist.add(new Student(101, "Zues", 26));
       arraylist.add(new Student(505, "Abey", 24));
       arraylist.add(new Student(809, "Vignesh", 32));

       /*Sorting based on Student Name*/
       System.out.println("Student Name Sorting:");
       Collections.sort(arraylist, Student.StuNameComparator);

       for(Student str: arraylist){
            System.out.println(str);
       }

       /* Sorting on Rollno property*/
       System.out.println("RollNum Sorting:");
       Collections.sort(arraylist, Student.StuRollno);
       for(Student str: arraylist){
            System.out.println(str);
       }
    }
}

输出:

Student Name Sorting:
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
[ rollno=101, name=Zues, age=26]
RollNum Sorting:
[ rollno=101, name=Zues, age=26]
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程