Comparator 是 Java 中的一個(gè)接口,用于定義對(duì)象之間的排序規(guī)則。它可以用于對(duì)集合中的對(duì)象進(jìn)行排序,或者用于自定義排序算法。
1. 常見(jiàn)的應(yīng)用場(chǎng)景
- 對(duì)集合中的對(duì)象進(jìn)行排序。
- 自定義排序算法。
- 結(jié)合 Stream流 實(shí)現(xiàn)更便捷的排序操作。
2. 基本使用
- 實(shí)現(xiàn) Comparator 接口:創(chuàng)建一個(gè)類(lèi),實(shí)現(xiàn) Comparator 接口,并重寫(xiě)其 compare 方法。在 compare 方法中定義排序規(guī)則。
- 匿名內(nèi)部類(lèi):使用匿名內(nèi)部類(lèi)的方式創(chuàng)建 Comparator 對(duì)象,并在其中實(shí)現(xiàn) compare 方法。
- Lambda 表達(dá)式:使用 Lambda 表達(dá)式簡(jiǎn)化 Comparator 的創(chuàng)建。
3. 常見(jiàn)用法
- 使用 Comparator.comparing 方法:Comparator 提供了 comparing 方法,可以根據(jù)對(duì)象的某個(gè)屬性進(jìn)行比較。
- 使用 Comparator.comparingInt、comparingLong、comparingDouble 方法:對(duì)于基本類(lèi)型的屬性,可以使用相應(yīng)的方法進(jìn)行比較。
4. 高級(jí)用法
- 逆序排序:通過(guò)調(diào)用 Comparator 的 reversed 方法可以實(shí)現(xiàn)逆序排序。
- 多級(jí)排序:可以通過(guò)鏈?zhǔn)秸{(diào)用多個(gè) Comparator 對(duì)象來(lái)實(shí)現(xiàn)多級(jí)排序。
- 自定義比較邏輯:在 compare 方法中可以根據(jù)自己的需求定義排序邏輯。
5. 示例代碼及解析
public class Student {
private String name;
private int score;
public 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 class ComparatorExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 90));
students.add(new Student("Bob", 80));
students.add(new Student("Charlie", 95));
// 按照分?jǐn)?shù)升序排序
// 使用匿名內(nèi)部類(lèi)實(shí)現(xiàn) Comparator 接口
/*students.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getScore()>o2.getScore() ? 1 : -1;
}
});*/
// 使用 Lambda 表達(dá)式實(shí)現(xiàn) Comparator 接口
students.sort(Comparator.comparing(student -> student.getScore()));
System.out.println("按照分?jǐn)?shù)升序排序: " + students);
// 按照分?jǐn)?shù)降序排序
students.sort(Comparator
.comparing((Student student) -> student.getScore())
.reversed());
System.out.println("按照分?jǐn)?shù)降序排序: " + students);
// 按照分?jǐn)?shù)降序排序,分?jǐn)?shù)相同則按照姓名升序排序
students.sort(Comparator
.comparing((Student student) -> student.getScore())
.reversed()
.thenComparing(student1 -> student1.getName()));
System.out.println("按照分?jǐn)?shù)降序、姓名升序排序: " + students);
// 自定義排序邏輯,按照字符串長(zhǎng)度排序
List<String> strings = new ArrayList<>();
strings.add("abc");
strings.add("defg");
strings.add("hijkl");
strings.sort(Comparator.comparing(s -> s.length()));
System.out.println("按照字符串長(zhǎng)度排序: " + strings);
}
}
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-809827.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-809827.html
到了這里,關(guān)于【java常用接口】Comparator學(xué)習(xí)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!