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

在Java中实现商品价格排序功能,通常可以通过集合类结合比较器(Comparator)来完成。假设我们有一个商品类 Product,包含名称和价格属性,目标是根据价格对商品列表进行升序或降序排序。
<pre class="brush:php;toolbar:false;">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 + '}';
}
}
方式一:使用 Collections.sort()
<pre class="brush:php;toolbar:false;">import java.util.*;
List<Product> 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(推荐,更灵活)
<pre class="brush:php;toolbar:false;">// 升序
List<Product> sortedAsc = products.stream()
.sorted(Comparator.comparing(Product::getPrice))
.toList();
// 降序
List<Product> sortedDesc = products.stream()
.sorted(Comparator.comparing(Product::getPrice).reversed())
.toList();
<pre class="brush:php;toolbar:false;">List<Product> sorted = products.stream()
.sorted(Comparator.comparing(Product::getPrice)
.thenComparing(Product::getName))
.toList();
<pre class="brush:php;toolbar:false;">Product{name='耳机', price=199.5}
Product{name='手机', price=2999.0}
Product{name='电脑', price=5999.9}
以上就是如何使用Java实现商品价格排序功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号