【定制排序、使用比较器】 商品属性Production // 价格、商品名、销量、评论数、客户收藏数量 现有商品的仓库,提供了三个方法 --商品集合【属性】 --实现商品的价格降序排序() --实现商品的价格升序序排序() --实现商品的排序(入参比较器【匿名内部类】)
时间: 2023-12-16 12:02:56 浏览: 36
排序比较器:按顺序排序,按顺序排序,插入和排序,选择排序,快速排序,比较排序
以下为可能的实现代码:
```java
public class Product {
private String name;
private double price;
private int sales;
private int comments;
private int favorites;
// getters and setters
// constructor
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", price=" + price +
", sales=" + sales +
", comments=" + comments +
", favorites=" + favorites +
'}';
}
}
public class ProductWarehouse {
private List<Product> products = new ArrayList<>();
public List<Product> getProducts() {
return products;
}
public void addProduct(Product product) {
products.add(product);
}
public void sortDescendingByPrice() {
products.sort((p1, p2) -> Double.compare(p2.getPrice(), p1.getPrice()));
}
public void sortAscendingByPrice() {
products.sort((p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()));
}
public void sort(Comparator<Product> comparator) {
products.sort(comparator);
}
}
```
使用示例:
```java
ProductWarehouse warehouse = new ProductWarehouse();
// add some products to the warehouse
// sort descending by price
warehouse.sortDescendingByPrice();
System.out.println(warehouse.getProducts());
// sort ascending by price
warehouse.sortAscendingByPrice();
System.out.println(warehouse.getProducts());
// sort by sales
warehouse.sort((p1, p2) -> Integer.compare(p2.getSales(), p1.getSales()));
System.out.println(warehouse.getProducts());
// sort by comments
warehouse.sort((p1, p2) -> Integer.compare(p2.getComments(), p1.getComments()));
System.out.println(warehouse.getProducts());
// sort by favorites
warehouse.sort((p1, p2) -> Integer.compare(p2.getFavorites(), p1.getFavorites()));
System.out.println(warehouse.getProducts());
```
阅读全文