當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Comparator Interface用法及代碼示例


比較器接口用於對用戶定義類的對象進行排序。比較器對象能夠比較同一類的兩個對象。以下函數將 obj1 與 obj2 進行比較。

用法:

public int compare(Object obj1, Object obj2):

假設我們有一個自己的類類型的Array/ArrayList,包含卷號、名稱、地址、出生日期等字段,並且我們需要根據卷號或名稱對數組進行排序?

方法 1:一種明顯的方法是使用一種標準算法編寫我們自己的 sort() 函數。該解決方案需要針對不同的標準(例如卷號和名稱)重寫整個排序代碼。

方法2:使用比較器接口 - Comparator 接口用於對用戶定義類的對象進行排序。該接口存在於java.util包中,包含2個方法compare(Object obj1, Object obj2)和equals(Object element)。使用比較器,我們可以根據數據成員對元素進行排序。例如,它可能是卷號、姓名、年齡或其他任何內容。

Collections 類對 List 元素進行排序的方法用於通過給定的比較器對 List 的元素進行排序。

public void sort(List list, ComparatorClass c)

要對給定列表進行排序,ComparatorClass 必須實現 Comparator 接口。

Collections 類的sort() 方法如何工作?

在內部,Sort 方法確實調用它正在排序的類的 Compare 方法。為了比較兩個元素,它會問“哪個更大?” Compare 方法返回 -1、0 或 1 來表示它是否小於、等於或大於另一個。然後它使用這個結果來確定是否應該交換它們的排序。

示例

Java


// Java Program to Demonstrate Working of 
// Comparator Interface
// Importing required classes 
import java.io.*;
import java.lang.*;
import java.util.*;
// Class 1
// A class to represent a Student
class Student {
    // Attributes of a student
    int rollno;
    String name, address;
    // Constructor
    public Student(int rollno, String name, String address)
    {
        // This keyword refers to current instance itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
    // Method of Student class
    // To print student details in main()
    public String toString()
    {
        // Returning attributes of Student
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
    // Method
    // Sorting in ascending order of roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
    // Method
    // Sorting in ascending order of name
    public int compare(Student a, Student b)
    {
        return a.name.compareTo(b.name);
    }
}
// Class 4
// Main class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of Student type
        ArrayList<Student> ar = new ArrayList<Student>();
        // Adding entries in above List
        // using add() method
        ar.add(new Student(111, "Mayank", "london"));
        ar.add(new Student(131, "Anshul", "nyc"));
        ar.add(new Student(121, "Solanki", "jaipur"));
        ar.add(new Student(101, "Aggarwal", "Hongkong"));
        // Display message on console for better readability
        System.out.println("Unsorted");
        // Iterating over entries to print them
        for (int i = 0; i < ar.size(); i++)
            System.out.println(ar.get(i));
        // Sorting student entries by roll number
        Collections.sort(ar, new Sortbyroll());
        // Display message on console for better readability
        System.out.println("\nSorted by rollno");
        // Again iterating over entries to print them
        for (int i = 0; i < ar.size(); i++)
            System.out.println(ar.get(i));
        // Sorting student entries by name
        Collections.sort(ar, new Sortbyname());
        // Display message on console for better readability
        System.out.println("\nSorted by name");
        // // Again iterating over entries to print them
        for (int i = 0; i < ar.size(); i++)
            System.out.println(ar.get(i));
    }
}
輸出
Unsorted
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong

Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc

Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur

通過更改比較方法內的返回值,您可以按您希望的任何順序排序,例如: 對於降序,隻需更改上述比較方法中‘a’ 和‘b’ 的位置即可。

Sort collection by more than one field

在前麵的示例中,我們討論了如何使用 Comparable 和 Comparator 接口根據單個字段對對象列表進行排序但是,如果我們需要根據多個字段對 ArrayList 對象進行排序,例如首先,根據學生姓名排序;其次,根據學生年齡排序。

示例

Java


// Java Program to Demonstrate Working of
// Comparator Interface Via More than One Field
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
// Class 1
// Helper class representing a Student
class Student {
    // Attributes of student
    String Name;
    int Age;
    // Parameterized constructor
    public Student(String Name, Integer Age)
    {
        // This keyword refers to current instance itself
        this.Name = Name;
        this.Age = Age;
    }
    // Getter setter methods
    public String getName() { return Name; }
    public void setName(String Name) { this.Name = Name; }
    public Integer getAge() { return Age; }
    public void setAge(Integer Age) { this.Age = Age; }
    // Method
    // Overriding toString() method
    @Override public String toString()
    {
        return "Customer{"
            + "Name=" + Name + ", Age=" + Age + '}';
    }
}
// Class 2
// Helper class implementing Comparator interface
class CustomerSortingComparator
    implements Comparator<Student> {
    // Method 1
    // To compare customers
    @Override
    public int compare(Student customer1, Student customer2)
    {
        // Comparing customers
        int NameCompare = customer1.getName().compareTo(
            customer2.getName());
        int AgeCompare = customer1.getAge().compareTo(
            customer2.getAge());
        // 2nd level comparison
        return (NameCompare == 0) ? AgeCompare
                                  : NameCompare;
    }
}
// Method 2
// Main driver method
class GFG {
    public static void main(String[] args)
    {
        // Create an empty ArrayList
        // to store Student
        List<Student> al = new ArrayList<>();
        // Create customer objects
        // using constructor initialization
        Student obj1 = new Student("Ajay", 27);
        Student obj2 = new Student("Sneha", 23);
        Student obj3 = new Student("Simran", 37);
        Student obj4 = new Student("Ajay", 22);
        Student obj5 = new Student("Ajay", 29);
        Student obj6 = new Student("Sneha", 22);
        // Adding customer objects to ArrayList
        // using add() method
        al.add(obj1);
        al.add(obj2);
        al.add(obj3);
        al.add(obj4);
        al.add(obj5);
        al.add(obj6);
        // Iterating using Iterator
        // before Sorting ArrayList
        Iterator<Student> custIterator = al.iterator();
        // Display message
        System.out.println("Before Sorting:\n");
        // Holds true till there is single element
        // remaining in List
        while (custIterator.hasNext()) {
            // Iterating using next() method
            System.out.println(custIterator.next());
        }
        // Sorting using sort method of Collections class
        Collections.sort(al,
                         new CustomerSortingComparator());
        // Display message only
        System.out.println("\n\nAfter Sorting:\n");
        // Iterating using enhanced for-loop
        // after Sorting ArrayList
        for (Student customer : al) {
            System.out.println(customer);
        }
    }
}
輸出
Before Sorting:

Customer{Name=Ajay, Age=27}
Customer{Name=Sneha, Age=23}
Customer{Name=Simran, Age=37}
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=29}
Customer{Name=Sneha, Age=22}


After Sorting:

Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}


相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Comparator Interface in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。