I was looking for a way to implement a Comparator for comparing products by name and price. I've found a lot of useful information here How to sort by two fields in Java? and have implemented my comparator.
It compares product names correctly but the prices are not in the right order. I'm expecting to have names in alphabetical order and prices in ascending order. How is it possible to achieve that? What am I missing here?
Here is what I've made so far:
A method to compare by name and price
public static List<BaseProduct> compareNamesAndPrices(List<BaseProduct> baseProducts) {
Comparator<BaseProduct> productComparator = Comparator.comparing(BaseProduct::getProductName)
.thenComparing(Comparator.comparing(BaseProduct::getPrice));
return baseProducts.stream()
.sorted(productComparator)
.collect(Collectors.toList());
}
Testing the method
List<BaseProduct> sortedProductsList = StaticUtils.compareNamesAndPrices(products);
for (BaseProduct product : sortedProductsList) {
System.out.println(String.format("Product name: %s -> Price: %s", product.getProductName(), product.getPrice().toString()));
}
And I'm getting the following output:
Product name: Bananas -> Price: 45
Product name: Galaxy 7 phone -> Price: 400
Product name: Xiaomi Mi5 -> Price: 370