Java Comparable और Comparator
In this page:
class ClassName implements Comparable<ClassName> {
public int compareTo(ClassName other) {
return Integer.compare(this.field, other.field);
}
}
Comparator<ClassName> comparator = Comparator.comparing(ClassName::getField);
Natural Sorting with Comparable
आप Comparable interface implement करके और इसके compareTo method को override करके अपनी खुद की custom classes के लिए एक default, natural sort order define कर सकते हैं। TreeSet और TreeMap जैसी collections अपने आप इस natural ordering का उपयोग करेंगी जब तक आप explicitly कुछ और न दें।
उदाहरण: Natural Sorting with Comparable
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
// Define the class Person
static class Person implements Comparable<Person> {
String name; int age;
Person(String name, int age) { this.name = name; this.age = age; }
public int compareTo(Person other) { return Integer.compare(age, other.age); }
public String toString() { return name + "(" + age + ")"; }
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new ArrayList object and store it in people
List<Person> people = new ArrayList<>(List.of(new Person("Bo", 30), new Person("Al", 20)));
Collections.sort(people);
// Print a line to the console
System.out.println(people);
}
}
Login to try C/C++/Java/PHP code in the editor
Custom Sorting with Comparator
अगर आप उन्हीं objects को उनकी class definition को बिना छुए कई अलग-अलग तरीकों से sort करना चाहते हैं, तो आप अपनी ज़रूरत के हर ordering के लिए Comparator interface implement करती एक अलग class define कर सकते हैं। यह sorting logic को उस object से पूरी तरह अलग कर देता है जिसे sort किया जा रहा है।
उदाहरण: Custom Sorting with Comparator
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
// Define the class ByName
static class ByName implements Comparator<String> {
public int compare(String a, String b) { return a.compareTo(b); }
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new ArrayList object and store it in names
List<String> names = new ArrayList<>(List.of("Zoe", "Amy", "Max"));
names.sort(new ByName());
// Print a line to the console
System.out.println(names);
}
}
Login to try C/C++/Java/PHP code in the editor
Comparator Lambda Syntax
आप सिर्फ एक comparison के लिए पूरी named class declare करने के बजाय lambda expressions उपयोग करके ad-hoc comparators तेज़ी से लिख सकते हैं। आधुनिक Java code में comparators लिखने का यह सबसे आम तरीका है, खासकर one-off sorts के लिए।
उदाहरण: Comparator Lambda Syntax
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new ArrayList object and store it in names
List<String> names = new ArrayList<>(List.of("Zoe", "Amy", "Max"));
names.sort((a, b) -> a.compareTo(b));
// Print a line to the console
System.out.println(names);
}
}
Login to try C/C++/Java/PHP code in the editor
Chaining Comparators
आप fallback sorting rules define करने के लिए thenComparing() method का उपयोग करके कई comparators को chain कर सकते हैं, ताकि जब दो elements primary comparison पर बराबर हों, तो chain में अगला comparator tie तोड़ दे, और इसी तरह आगे chain में।
उदाहरण: Chaining Comparators
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
// Define the record Person (an immutable data carrier)
record Person(String name, int age) {}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new ArrayList object and store it in people
List<Person> people = new ArrayList<>(List.of(new Person("Amy", 30), new Person("Amy", 20)));
people.sort(Comparator.comparing(Person::name).thenComparing(Person::age));
// Print a line to the console
System.out.println(people);
}
}
Login to try C/C++/Java/PHP code in the editor
Null-Safe Comparators
null elements रखने वाली किसी collection को custom comparator से sort करने पर उस क्षण NullPointerException फेंक सकता है जब comparator इसे किसी से compare करने की कोशिश करे। आप इसके खिलाफ अपने comparator को Comparator.nullsFirst() या nullsLast() से wrap करके guard कर सकते हैं, जो nulls को आपकी चुनी ordering के जिस भी छोर पर धकेल देते हैं।
उदाहरण: Null-Safe Comparators
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Create a new ArrayList object and store it in names
List<String> names = new ArrayList<>(Arrays.asList("Zoe", null, "Amy"));
names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
// Print a line to the console
System.out.println(names);
}
}
Login to try C/C++/Java/PHP code in the editor
Comparableimplement न करने वाली किसी class परCollections.sort(list)call करना, जो compile नहीं होता;Comparableimplement करें या एक Comparator पास करें।- किसी comparator को
a.age - b.ageके रूप में लिखना, जो बड़ी values के लिए overflow हो सकता है;Integer.compare(a.age, b.age)का उपयोग करें। nullvalues वाली किसी list को एक साधारण comparator से sort करना, जोNullPointerExceptionफेंकता है; इसेComparator.nullsFirstसे wrap करें।
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: