Java में List Sorting
In this page:
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()
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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()
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
- एक comparator से sort करना जो values subtract करता है, जैसे
a - b, जो overflow कर सकता है;Integer.compare(a, b)उपयोग करें। - एक immutable list पर
Collections.sort()उपयोग करना, जोUnsupportedOperationExceptionthrow करता है। - बिना comparator वाले custom objects के लिए
Comparableimplement करना भूल जाना।
- Collections framework
ArrayList,LinkedList,HashMap,TreeMap,HashSet, औरTreeSetजैसे implementations के साथList,Set, औरMapinterfaces प्रदान करता है। LinkedHashMapऔरLinkedHashSetजैसे Linked और ordered variants एक predictable order रखते हैं।Stack,Queue,Iterator,Collectionsclass, और list sorting data structures के साथ काम करने को round out करते हैं।
Chapter Quiz — Complete all 17 topics to unlock
0/17 topics done
Complete these topics first:
- Java Data Structures
- Java Collections Introduction
- Java List Interface
- Java ArrayList
- Java LinkedList
- Java Map Interface
- Java HashMap
- Java Set Interface
- Java TreeMap
- Java LinkedHashMap
- Java HashSet
- Java TreeSet
- Java LinkedHashSet
- Java Stack & Queue
- Java Iterator
- Java Collections Class
- Java List Sorting