🔹 Introduction
Sorting is one of the most fundamental operations in programming and is frequently asked in Java interviews.
👉 In this article, we will learn how to sort a list using:
- Traditional approach
- Java Streams (modern approach)
🔹 Problem Statement
Given a list of integers, sort it in ascending and descending order.
Example:
Input: [5, 2, 8, 1, 3]
Output: Ascending: [1, 2, 3, 5, 8]
Descending: [8, 5, 3, 2, 1]
🔹 Approach 1: Using Collections.sort()
💡 Explanation
- Use built-in sorting method
- Works directly on list
👨💻 Java Code
import java.util.*;
public class SortList {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5,2,8,1,3);
Collections.sort(list);
System.out.println("Ascending: " + list);
Collections.sort(list, Collections.reverseOrder());
System.out.println("Descending: " + list);
}
}
🔹 Approach 2: Using Java Streams (Recommended)
💡 Explanation
-
Use
sorted()method - Use comparator for descending
👨💻 Java Code (Streams)
import java.util.*;
import java.util.stream.*;
public class SortList {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5,2,8,1,3);
List<Integer> asc = list.stream()
.sorted()
.toList();
List<Integer> desc = list.stream()
.sorted(Comparator.reverseOrder())
.toList();
System.out.println("Ascending: " + asc);
System.out.println("Descending: " + desc);
}
}
🔹 Output
Ascending: [1, 2, 3, 5, 8]
Descending: [8, 5, 3, 2, 1]
🔹 Time Complexity
- O(n log n)
🔹 Key Takeaways
✔ sorted() is key method in streams
✔ Comparator helps customize sorting
✔ Very common interview question
🔹 Conclusion
Sorting using Streams is clean and efficient.
Make sure you understand both approaches for interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
👉 Reverse a String
👉 Count Character Frequency in Java
Comments
Post a Comment