Java 集合 Comparator接口

来源:这里教程网 时间:2026-02-17 20:13:39 作者:

在上一个教程中,我们已经了解了如何使用Comparable接口对自定义类的对象进行排序。通过使用Comparable,我们可以根据任何数据成员对对象进行排序。例如,假设我们有一个Author类有数据成员:作者姓名,书名和作者年龄,现在如果我们想根据任何数据成员对对象进行排序那么我们可以使用Comparable但是如果我们想要有多个排序选项,并且我们可以根据任何选择对对象进行排序,这可以使用Comparator接口完成,我们可以创建尽可能多的Comparator然后我们可以在一个或多个上调用Collections.sort这样的比较器:

//Sorting arraylist al by Author AgeCollections.sort(al, new AuthorAgeComparator());//Sorting arraylist al by Book NameCollections.sort(al, new BookNameComparator());

那么它是怎样工作的?要像这样调用Collections.sort方法,我们必须首先编写这些Comparator类AuthorAgeComparator和BookNameComparator,以及Author类和Main类。

完整的比较示例

Author.java

public class Author implements Comparable<Author> {  String firstName;   String bookName;   int auAge;   Author(String first, String book, int age){     this.firstName = first;     this.bookName = book;     this.auAge = age;   }   public String getFirstName() {     return firstName;   }  public void setFirstName(String firstName) {     this.firstName = firstName;   }  public String getBookName() {     return bookName;   }  public void setBookName(String bookName) {     this.bookName = bookName;   }  public int getAuAge() {     return auAge;   }  public void setAuAge(int auAge) {     this.auAge = auAge;   }   @Override   /*    * When we only use Comparable, this is where we write sorting   * logic. This method is called when we implement the Comparable   * interface in our class and call Collections.sort()   */   public int compareTo(Author au){             return this.firstName.compareTo(au.firstName);     }}

AuthorAgeComparator.java

import java.util.*;class AuthorAgeComparator implements Comparator<Author>{   public int compare(Author a1,Author a2){     if(a1.auAge==a2.auAge)       return 0;   else if(a1.auAge>a2.auAge)       return 1;   else       return -1;  }}

BookNameComparator.java

import java.util.*; public class BookNameComparator implements Comparator<Author>{   public int compare(Author a1,Author a2){        return a1.bookName.compareTo(a2.bookName);   }  }

SortingPgm.java

import java.util.ArrayList;  import java.util.Collections;public class SortingPgm{        public static void main(String args[]){         // List of objects of Author class           ArrayList<Author> al=new ArrayList<Author>();             al.add(new Author("Henry", "Tropic of Cancer",  45));     al.add(new Author("Nalo", "Brown Girl in the Ring", 56));     al.add(new Author("Frank", "300", 65));     al.add(new Author("Deborah", "Sky Boys", 51));     al.add(new Author("George R. R.", "A Song of Ice and Fire", 62));     /*             * Sorting the list using Collections.sort() method, we             * can use this method because we have implemented the              * Comparable interface in our user defined class Author             */           System.out.println("Sorting by Author First Name:");           Collections.sort(al);             for(Author au: al){              System.out.println(au.getFirstName()+", "+au.getBookName()+", "+           au.getAuAge());             }      /*Sorting using AuthorAgeComparator*/           System.out.println("Sorting by Author Age:");     Collections.sort(al, new AuthorAgeComparator());     for(Author au: al){              System.out.println(au.getFirstName()+", "+au.getBookName()+", "+          au.getAuAge());             }                  /*Sorting using BookNameComparator*/           System.out.println("Sorting by Book Name:");           Collections.sort(al, new BookNameComparator());           for(Author au: al){               System.out.println(au.getFirstName()+", "+au.getBookName()+", "+            au.getAuAge());            }      }  }  

输出:

Sorting by Author First Name:Deborah, Sky Boys, 51Frank, 300, 65George R. R., A Song of Ice and Fire, 62Henry, Tropic of Cancer, 45Nalo, Brown Girl in the Ring, 56Sorting by Author Age:Henry, Tropic of Cancer, 45Deborah, Sky Boys, 51Nalo, Brown Girl in the Ring, 56George R. R., A Song of Ice and Fire, 62Frank, 300, 65Sorting by Book Name:Frank, 300, 65George R. R., A Song of Ice and Fire, 62Nalo, Brown Girl in the Ring, 56Deborah, Sky Boys, 51Henry, Tropic of Cancer, 45

相关推荐