비교기 인터페이스는 사용자 정의 클래스의 개체를 정렬하는 데 사용됩니다. 비교자 객체는 동일한 클래스의 두 객체를 비교할 수 있습니다. . 다음 함수는 obj1과 obj2를 비교합니다.
통사론:
public int compare(Object obj1, Object obj2):>
롤 번호, 이름, 주소, DOB 등과 같은 필드를 포함하는 자체 클래스 유형의 Array/ArrayList가 있고 롤 번호 또는 이름을 기준으로 배열을 정렬해야 한다고 가정해 보겠습니다.
방법 1 : 한 가지 확실한 접근 방식은 표준 알고리즘 중 하나를 사용하여 자체 sort() 함수를 작성하는 것입니다. 이 솔루션을 사용하려면 롤 번호 및 이름과 같은 다양한 기준에 대해 전체 정렬 코드를 다시 작성해야 합니다.
자바 예외
방법 2: 비교기 인터페이스 사용 - 비교기 인터페이스는 사용자 정의 클래스의 개체를 정렬하는 데 사용됩니다. 이 인터페이스는 java.util 패키지에 있으며 Compare(Object obj1, Object obj2) 및 equals(Object 요소) 2가지 메서드를 포함합니다. 비교기를 사용하면 데이터 멤버를 기준으로 요소를 정렬할 수 있습니다. 예를 들어, 목록 번호, 이름, 나이 등이 있을 수 있습니다.
List 요소를 정렬하기 위한 Collections 클래스의 방법은 주어진 비교자로 List의 요소를 정렬하는 데 사용됩니다.
public void sort(List list, ComparatorClass c)>
주어진 목록을 정렬하려면 ComparatorClass가 Comparator 인터페이스를 구현해야 합니다.
Collections 클래스의 sort() 메서드는 어떻게 작동하나요?
내부적으로 Sort 메서드는 정렬 중인 클래스의 Compare 메서드를 호출합니다. 두 요소를 비교하려면 어느 것이 더 큰가요?라고 묻습니다. 비교 메소드는 -1, 0 또는 1을 반환하여 다른 것보다 작거나 같거나 큰지를 나타냅니다. 그런 다음 이 결과를 사용하여 정렬을 위해 교체해야 하는지 결정합니다.
예
자바
// 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 {> >// 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 {> >// 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 ar =>new> ArrayList();> >// 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 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('
Sorted by rollno'); // Again iterating over entries to print them for (int i = 0; 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('
Sorted by name'); // // Again iterating over entries to print them for (int i = 0; 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'의 위치를 변경하면 됩니다.
둘 이상의 필드를 기준으로 컬렉션 정렬
이전 예에서는 Comparable 및 Comparator 인터페이스를 사용하여 단일 필드를 기준으로 개체 목록을 정렬하는 방법을 논의했습니다. 그러나 첫 번째와 같이 두 개 이상의 필드에 따라 ArrayList 개체를 정렬해야 하는 경우에는 어떻게 해야 할까요? 학생 이름에 따라 정렬하고, 두 번째로 학생 나이에 따라 정렬합니다.
예
자바
// 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 {> >// 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 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 custIterator = al.iterator();> >// Display message> >System.out.println(>'Before Sorting:
'>);> >// 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(>'
After Sorting:
'>);> >// Iterating using enhanced for-loop> >// after Sorting ArrayList> >for> (Student customer : al) {> >System.out.println(customer);> >}> >}> }> |
>
JSON 파일을 읽는 방법
>산출
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}>