java怎么自定义排序规则

37次阅读
没有评论

共计 1060 个字符,预计需要花费 3 分钟才能阅读完成。

要自定义排序规则,可以使用 Comparator 接口来实现。Comparator 接口包含一个 compare 方法,用于定义自定义排序规则。

下面是一个例子,假设有一个 Student 类,其中包含姓名和年龄属性,我们希望按照年龄从大到小的顺序对 Student 对象进行排序:

import java.util.Comparator;

public class Student {
    private String name;
    private int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {return name;}
    
    public int getAge() {return age;}
}

public class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {if (s1.getAge() < s2.getAge()) {return 1;} else if (s1.getAge() > s2.getAge()) {return -1;} else {return 0;}
    }
}

然后在使用时,可以将 AgeComparator 传入 Collections.sort 方法中,这样就可以按照自定义的排序规则对 Student 对象进行排序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {public static void main(String[] args) {List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 22));
        students.add(new Student("Charlie", 18));
        
        Collections.sort(students, new AgeComparator());
        
        for (Student student : students) {System.out.println(student.getName() + " - " + student.getAge());
        }
    }
}

运行结果将会按照年龄从大到小的顺序输出学生信息。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-27发表,共计1060字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)