如何使用Java实现商品价格排序功能

答案:通过Comparator结合List实现商品价格排序。定义Product类后,使用Collections.sort()或Stream API按价格升序或降序排序,支持多条件比较,代码清晰且可扩展。

在Java中实现商品价格排序功能,通常可以通过集合类结合比较器(Comparator)来完成。假设我们有一个商品类 Product,包含名称和价格属性,目标是根据价格对商品列表进行升序或降序排序。

1. 定义商品类 Product

首先创建一个简单的商品类,包含基本属性如名称和价格,并提供构造方法和 getter 方法:

public class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Product{name='" + name + "', price=" + price + '}';

} }

2. 使用 List 和 Comparator 排序

将多个商品放入 ArrayList 中,然后使用 Collections.sort() 或 Stream API 结合自定义比较器按价格排序。

方式一:使用 Collections.sort()

import java.util.*;

List products = new ArrayList<>();
products.add(new Product("手机", 2999.0));
products.add(new Product("耳机", 199.5));
products.add(new Product("电脑", 5999.9));

// 按价格升序排序
Collections.sort(products, Comparator.comparing(Product::getPrice));

// 输出结果
products.forEach(System.out::println);

方式二:使用 Stream API(推荐,更灵活)

// 升序
List sortedAsc = products.stream()
    .sorted(Comparator.comparing(Product::getPrice))
    .toList();

// 降序
List sortedDesc = products.stream()
    .sorted(Comparator.comparing(Product::getPrice).reversed())
    .toList();

3. 处理价格相同的情况(可选)

如果多个商品价格相同,可以添加次要排序条件,比如按名称字母顺序排序:
List sorted = products.stream()
    .sorted(Comparator.comparing(Product::getPrice)
                .thenComparing(Product::getName))
    .toList();

4. 完整示例运行效果

执行上述代码后输出(升序):
Product{name='耳机', price=199.5}
Product{name='手机', price=2999.0}
Product{name='电脑', price=5999.9}
基本上就这些。通过 Java 的 Comparator 配合集合或流操作,可以轻松实现商品价格排序,逻辑清晰且易于扩展。