Skip to content

Commit 4dabc3d

Browse files
committed
feat(ListDemo): add demo of sorting lists with Collections.sort and List.sort
What - Added ListDemo class. - Created a List<Integer> with values [1,3,2]. - Demonstrated sorting with list.sort(null), which uses natural ordering (ascending). - Created a List<String> with values ["banana","apple","date"]. - Sorted words with list.sort(null) (alphabetical order). - Printed sorted results. Why - Shows two equivalent ways of sorting lists: - Collections.sort(list). - list.sort(null) (preferred since Java 8). - Demonstrates natural ordering: - For integers → ascending numeric order. - For strings → lexicographical order. How - list = [1,3,2]. - list.sort(null) → [1,2,3]. - words = ["banana","apple","date"]. - words.sort(null) → ["apple","banana","date"]. - Printed both lists. Logic - Inputs: integer and string lists. - Outputs: - Sorted integers ascending. - Sorted strings alphabetically. - Flow: 1. Initialize lists. 2. Sort integers with list.sort(null). 3. Sort strings with list.sort(null). 4. Print results. - Edge cases: - Passing null to sort() means use natural ordering. - For custom order, pass Comparator (e.g., Comparator.reverseOrder()). - Complexity: O(n log n) sort. - Concurrency: Not thread-safe if list is modified concurrently. Real-life applications - Sorting numerical or textual data for reporting, searching, or UI display. - Using natural ordering without writing explicit comparators. - Switching between natural and custom order by replacing null with Comparator. Notes - Collections.sort(list) and list.sort(null) are interchangeable; list.sort is more modern and direct. - Natural ordering is defined by Comparable implementation of list elements. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 3acfa5e commit 4dabc3d

File tree

1 file changed

+3
-5
lines changed
  • Section 25 Collections Frameworks/List Interface/ArrayList/src

1 file changed

+3
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
package ListDemo.ArrayListLinkedListStack;
2-
31
import java.util.*;
42

5-
public class ListEDSort {
3+
public class ListDemo {
64
public static void main(String[] args) {
75
List<Integer> list = new ArrayList<>();
86
list.add(1);
@@ -11,12 +9,12 @@ public static void main(String[] args) {
119

1210
//Collections.sort(list);
1311

14-
//Other method using comparator
12+
//Another method using comparator.
1513
list.sort(null);
1614
System.out.println(list);
1715

1816
List<String> words = Arrays.asList("banana","apple","date");
1917
words.sort(null);
2018
System.out.println(words);
2119
}
22-
}
20+
}

0 commit comments

Comments
 (0)