Practical Ordering Examples
Real-World Sorting Scenarios
Practical ordering demonstrates how custom sorting strategies solve complex real-world problems across different domains.
Example 1: Student Management System
public class StudentSorting {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 85.5, 22),
new Student("Bob", 92.3, 21),
new Student("Charlie", 78.1, 23)
);
// Multi-criteria sorting
Collections.sort(students,
Comparator.comparing(Student::getGrade)
.thenComparing(Student::getAge)
.reversed()
);
}
}
class Student {
private String name;
private double grade;
private int age;
// Constructor, getters, methods
}
Sorting Strategy Workflow
graph TD
A[Input Collection] --> B[Define Comparator]
B --> C[Apply Sorting Strategy]
C --> D[Sorted Collection]
D --> E[Further Processing]
Example 2: Product Inventory Management
public class ProductOrdering {
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
// Complex sorting with multiple criteria
products.sort(
Comparator.comparing(Product::getCategory)
.thenComparing(Product::getPrice)
.thenComparing(Product::getName)
);
}
}
Sorting Complexity Levels
Complexity |
Description |
Example |
Simple |
Single attribute |
Price sorting |
Intermediate |
Multiple attributes |
Category + Price |
Advanced |
Complex logic |
Custom scoring |
Example 3: Log Entry Analysis
public class LogEntrySort {
public static void main(String[] args) {
List<LogEntry> logs = getLogs();
// Null-safe, timestamp-based sorting
logs.sort(
Comparator.comparing(LogEntry::getTimestamp, Comparator.nullsLast(Comparator.naturalOrder()))
);
}
}
- Use primitive comparisons
- Minimize object creation
- Leverage method references
- Implement efficient comparison logic
Advanced Ordering Techniques
// Custom weighted sorting
Comparator<Product> weightedComparator = (p1, p2) -> {
double score1 = calculateProductScore(p1);
double score2 = calculateProductScore(p2);
return Double.compare(score1, score2);
};
Common Sorting Patterns
graph LR
A[Sorting Patterns] --> B[Natural Ordering]
A --> C[Reverse Ordering]
A --> D[Multi-Attribute]
A --> E[Null-Safe]
Best Practices
- Choose the right sorting strategy
- Consider performance implications
- Test edge cases thoroughly
- Use built-in Java comparator methods
- Keep sorting logic clean and readable
By mastering these practical ordering examples, developers can create sophisticated sorting mechanisms tailored to specific application requirements.