← Back to Core Java Course | Chapter 11: Collections | Lesson 17 of 17

Java में List Sorting

एक list sort करना इसके items को order में रखता है, kids को height से line up करने जैसा। आप natural order उपयोग कर सकते हैं या पहले क्या आए इसके लिए अपना खुद का rule लिख सकते हैं।
Syntax
java
Collections.sort(list);
list.sort(Comparator.comparing(Type::getField));

Sorting with Collections.sort()

Static method Collections.sort(list) हर element की natural ordering उपयोग करके एक List को जगह पर sort करता है, जिसे elements को Comparable implement करने की ज़रूरत है।

यह original Collections Framework के समय से Java का हिस्सा रहा है और Java 8 से पहले लिखे code में अब भी आम है।

उदाहरण: Sorting with Collections.sort()

java
import java.util.Collections;
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> nums = new ArrayList<>(java.util.List.of(3, 1, 2));
		Collections.sort(nums); // natural ordering, requires Comparable
		System.out.println(nums);
	}
}

Sorting with List.sort()

Java 8 से, हर List का अपना instance method list.sort(comparator) है, जो अक्सर Collections.sort() से ज़्यादा पसंद किया जाता है क्योंकि यह ज़्यादा naturally पढ़ता है और आपको natural ordering पर fall back करने के लिए null pass करने देता है।

दोनों methods एक नई sorted list return करने के बजाय list को जगह पर sort करते हैं।

उदाहरण: Sorting with List.sort()

java
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> nums = new ArrayList<>(java.util.List.of(3, 1, 2));
		nums.sort(null); // null falls back to natural ordering
		System.out.println(nums);
	}
}

Natural Ordering via Comparable

एक class Comparable<T> और इसका compareTo() method implement करके अपना default sort order define करती है, less-than, equal-to, या greater-than indicate करने के लिए negative, zero, या positive return करते हुए।

String और Integer जैसे Built-in types पहले से Comparable implement करते हैं, यही कारण है कि उनकी lists बिना किसी extra setup के सही sort होती हैं।

उदाहरण: Natural Ordering via Comparable

java
// Define the class Person
class Person implements Comparable<Person> {
	int age;
	Person(int age) { this.age = age; }
	public int compareTo(Person other) {
		// Send this.age - other.age back to the caller
		return this.age - other.age;
	}
}
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		java.util.ArrayList<Person> people = new java.util.ArrayList<>();
		people.add(new Person(30));
		people.add(new Person(20));
		java.util.Collections.sort(people);
		// Print a line to the console
		System.out.println(people.get(0).age);
	}
}

Custom Ordering via Comparator Lambda

जब आपको natural वाले से अलग एक sort order चाहिए, या आप एक class sort कर रहे हैं जिसे आप modify नहीं कर सकते, इसके बजाय एक Comparator pass करें — list.sort((a, b) -> a.getAge() - b.getAge()) जैसा एक lambda एक बिल्कुल अलग field से sort करता है।

Comparable के विपरीत, एक class अपना code बदले बिना कई अलग comparators रख सकती है।

उदाहरण: Custom Ordering via Comparator Lambda

java
// Import java.util.ArrayList so it can be used by its short name
import java.util.ArrayList;
// Define the class Person
class Person {
	int age;
	Person(int age) { this.age = age; }
}
// 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 people
		ArrayList<Person> people = new ArrayList<>();
		people.add(new Person(30));
		people.add(new Person(20));
		people.sort((a, b) -> a.age - b.age);
		// Print a line to the console
		System.out.println(people.get(0).age);
	}
}

Sorting by Multiple Keys

Comparator.comparing() और .thenComparing() methods आपको एक multi-level sort बनाने देते हैं, उदाहरण के लिए लोगों को last name से sort करना और first name को सिर्फ tiebreaker के रूप में उपयोग करना जब last names match करें।

यह left से right clearly पढ़ता है और एक compareTo() या lambda body के अंदर एक लंबी manual if/else chain लिखने से बचता है।

उदाहरण: Sorting by Multiple Keys

java
// Import java.util.ArrayList so it can be used by its short name
import java.util.ArrayList;
// Import java.util.Comparator so it can be used by its short name
import java.util.Comparator;
// Define the class Person
class Person {
	String lastName, firstName;
	Person(String lastName, String firstName) {
		this.lastName = lastName;
		this.firstName = firstName;
	}
}
// 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 people
		ArrayList<Person> people = new ArrayList<>();
		people.add(new Person("Smith", "Bob"));
		people.add(new Person("Smith", "Alice"));
		people.sort(Comparator.comparing((Person p) -> p.lastName)
				.thenComparing(p -> p.firstName));
		// Print a line to the console
		System.out.println(people.get(0).firstName);
	}
}
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. एक comparator से sort करना जो values subtract करता है, जैसे a - b, जो overflow कर सकता है; Integer.compare(a, b) उपयोग करें।
  2. एक immutable list पर Collections.sort() उपयोग करना, जो UnsupportedOperationException throw करता है।
  3. बिना comparator वाले custom objects के लिए Comparable implement करना भूल जाना।
चैप्टर सारांश
  • Collections framework ArrayList, LinkedList, HashMap, TreeMap, HashSet, और TreeSet जैसे implementations के साथ List, Set, और Map interfaces प्रदान करता है।
  • LinkedHashMap और LinkedHashSet जैसे Linked और ordered variants एक predictable order रखते हैं।
  • Stack, Queue, Iterator, Collections class, और list sorting data structures के साथ काम करने को round out करते हैं।

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.