← Back to Advanced Java Course | Chapter 5: Collections Advanced | Lesson 3 of 4

Java Comparable और Comparator

Comparable और Comparator Java को बताते हैं कि objects को order में कैसे रखा जाए, जैसे बच्चों को height या name के अनुसार लाइन में खड़ा करने के नियम। Comparable natural नियम है, और Comparator आपका चुना हुआ नियम है।
Syntax
java
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

java
// 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);
	}
}

Custom Sorting with Comparator

अगर आप उन्हीं objects को उनकी class definition को बिना छुए कई अलग-अलग तरीकों से sort करना चाहते हैं, तो आप अपनी ज़रूरत के हर ordering के लिए Comparator interface implement करती एक अलग class define कर सकते हैं। यह sorting logic को उस object से पूरी तरह अलग कर देता है जिसे sort किया जा रहा है।

उदाहरण: Custom Sorting with Comparator

java
// 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);
	}
}

Comparator Lambda Syntax

आप सिर्फ एक comparison के लिए पूरी named class declare करने के बजाय lambda expressions उपयोग करके ad-hoc comparators तेज़ी से लिख सकते हैं। आधुनिक Java code में comparators लिखने का यह सबसे आम तरीका है, खासकर one-off sorts के लिए।

उदाहरण: Comparator Lambda Syntax

java
// 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);
	}
}

Chaining Comparators

आप fallback sorting rules define करने के लिए thenComparing() method का उपयोग करके कई comparators को chain कर सकते हैं, ताकि जब दो elements primary comparison पर बराबर हों, तो chain में अगला comparator tie तोड़ दे, और इसी तरह आगे chain में।

उदाहरण: Chaining Comparators

java
// 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);
	}
}

Null-Safe Comparators

null elements रखने वाली किसी collection को custom comparator से sort करने पर उस क्षण NullPointerException फेंक सकता है जब comparator इसे किसी से compare करने की कोशिश करे। आप इसके खिलाफ अपने comparator को Comparator.nullsFirst() या nullsLast() से wrap करके guard कर सकते हैं, जो nulls को आपकी चुनी ordering के जिस भी छोर पर धकेल देते हैं।

उदाहरण: Null-Safe Comparators

java
// 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);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Comparable implement न करने वाली किसी class पर Collections.sort(list) call करना, जो compile नहीं होता; Comparable implement करें या एक Comparator पास करें।
  2. किसी comparator को a.age - b.age के रूप में लिखना, जो बड़ी values के लिए overflow हो सकता है; Integer.compare(a.age, b.age) का उपयोग करें।
  3. null values वाली किसी list को एक साधारण comparator से sort करना, जो NullPointerException फेंकता है; इसे Comparator.nullsFirst से wrap करें।
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.