Careeroza
Real World Example
Sorting Hotel Search Results
Travel sites like MakeMyTrip let users sort hotels by "Popularity", "Price: Low to High" or "Rating". Each option is just a different Comparator chosen at runtime.
Example
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class Main {
record Hotel(String name, int price, double rating, int reviews) { }
static final Map<String, Comparator<Hotel>> SORTS = Map.of(
"price", Comparator.comparingInt(Hotel::price).thenComparing(Hotel::name),
"rating", Comparator.comparingDouble(Hotel::rating).reversed().thenComparingInt(Hotel::price),
"popular", Comparator.comparingInt(Hotel::reviews).reversed());
public static void main(String[] args) {
List<Hotel> hotels = List.of(
new Hotel("Sea View", 4200, 4.4, 1200),
new Hotel("City Inn", 2100, 3.9, 3400),
new Hotel("Palm Stay", 4200, 4.7, 800),
new Hotel("Budget Rooms", 1500, 4.4, 560));
for (String option : List.of("price", "rating", "popular")) {
List<Hotel> sorted = new ArrayList<>(hotels);
sorted.sort(SORTS.get(option));
System.out.println("Sort by " + option + ":");
sorted.forEach(h -> System.out.printf(" %-12s Rs %d %.1f* %d reviews%n", h.name(), h.price(), h.rating(), h.reviews()));
}
}
}Output
Sort by price: Budget Rooms Rs 1500 4.4* 560 reviews City Inn Rs 2100 3.9* 3400 reviews Palm Stay Rs 4200 4.7* 800 reviews Sea View Rs 4200 4.4* 1200 reviews Sort by rating: Palm Stay Rs 4200 4.7* 800 reviews Budget Rooms Rs 1500 4.4* 560 reviews Sea View Rs 4200 4.4* 1200 reviews City Inn Rs 2100 3.9* 3400 reviews Sort by popular: City Inn Rs 2100 3.9* 3400 reviews Sea View Rs 4200 4.4* 1200 reviews Palm Stay Rs 4200 4.7* 800 reviews Budget Rooms Rs 1500 4.4* 560 reviews
Practice
Exercise: Sort a list of Order(String id, LocalDate date, int amount) records: newest date first, and for the same date, highest amount first.
Show answer
orders.sort(Comparator.comparing(Order::date).reversed()
.thenComparing(Comparator.comparingInt(Order::amount).reversed()));