Practical Sorting Examples
Real-World Sorting Scenarios
TreeMap's flexible sorting capabilities enable developers to solve complex data organization challenges across various domains.
1. Employee Management System
class Employee {
String name;
int age;
double salary;
}
TreeMap<Employee, String> employeeRegistry = new TreeMap<>((e1, e2) -> {
// Sort by salary in descending order
int salaryComparison = Double.compare(e2.salary, e1.salary);
// Secondary sorting by age
if (salaryComparison == 0) {
return Integer.compare(e1.age, e2.age);
}
return salaryComparison;
});
2. Inventory Management
graph TD
A[Inventory Sorting] --> B[By Price]
A --> C[By Quantity]
A --> D[By Category]
A --> E[Composite Sorting]
Inventory Sorting Implementation
class Product {
String category;
double price;
int quantity;
}
TreeMap<Product, Integer> inventoryMap = new TreeMap<>((p1, p2) -> {
// Primary sort by category
int categoryCompare = p1.category.compareTo(p2.category);
// Secondary sort by price
if (categoryCompare == 0) {
return Double.compare(p1.price, p2.price);
}
return categoryCompare;
});
3. Student Grade Management
Sorting Criteria |
Description |
Primary Sort |
Grade Average |
Secondary Sort |
Student Name |
Tertiary Sort |
Age |
class Student {
String name;
int age;
double gradeAverage;
}
TreeMap<Student, String> studentRanking = new TreeMap<>((s1, s2) -> {
// Sort by grade average in descending order
int gradeComparison = Double.compare(s2.gradeAverage, s1.gradeAverage);
// Secondary sort by name
if (gradeComparison == 0) {
int nameComparison = s1.name.compareTo(s2.name);
// Tertiary sort by age
if (nameComparison == 0) {
return Integer.compare(s1.age, s2.age);
}
return nameComparison;
}
return gradeComparison;
});
4. Event Scheduling System
class Event {
LocalDateTime timestamp;
String priority;
}
TreeMap<Event, String> eventSchedule = new TreeMap<>((e1, e2) -> {
// Sort by timestamp
int timeComparison = e1.timestamp.compareTo(e2.timestamp);
// Secondary sort by priority
if (timeComparison == 0) {
return e1.priority.compareTo(e2.priority);
}
return timeComparison;
});
In LabEx platform development, practical sorting strategies:
- Enhance data organization
- Improve search efficiency
- Provide flexible data management solutions
- Minimize comparison complexity
- Use primitive comparisons when possible
- Consider memory and computational overhead
- Test with representative datasets
Key Takeaways
- Custom comparators enable complex sorting logic
- Multiple sorting criteria can be implemented
- TreeMap provides efficient, ordered data storage
By mastering these practical sorting techniques, developers can create more intelligent and responsive applications.