CodexBloom - Programming Q&A Platform

Sorting a List of Product Objects with Conditional Discounts in Java - Unexpected Ordering Issues

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-08-21
java sorting collections comparator Java

I'm reviewing some code and I'm working on a project and hit a roadblock. I'm working on a Java application where I need to sort a list of `Product` objects based on their prices. However, there's a twist: certain products have a discount status that affects their final prices. I'm trying to sort the products such that discounted products appear first, and within those, they should be sorted by their discounted prices. Non-discounted products should follow, sorted by their original prices. Here’s the `Product` class that I'm using: ```java public class Product { private String name; private double price; private boolean isDiscounted; // constructor, getters, and setters } ``` I tried implementing a custom comparator like this: ```java Collections.sort(products, new Comparator<Product>() { @Override public int compare(Product p1, Product p2) { if (p1.isDiscounted() && !p2.isDiscounted()) { return -1; // p1 comes before p2 } else if (!p1.isDiscounted() && p2.isDiscounted()) { return 1; // p2 comes before p1 } else if (p1.isDiscounted() && p2.isDiscounted()) { return Double.compare(p1.getDiscountedPrice(), p2.getDiscountedPrice()); } else { return Double.compare(p1.getPrice(), p2.getPrice()); } } }); ``` However, I'm running into issues where the products are not sorted as expected. For example, when I print the sorted list, discounted products are sometimes placed after non-discounted ones, which makes no sense. I've verified that the `isDiscounted()` method is returning the correct values, but it seems like the comparisons are not behaving as intended. I’m using Java 17, and I'm wondering if there’s something I might be missing regarding how the comparator is supposed to work, or if there’s a better way to handle this sorting logic. Has anyone encountered similar issues or have suggestions on how to improve this? How would you solve this? Is this even possible? My team is using Java for this REST API.