集合List练习 // a.创建商品类,属性:商品编号、商品名称、商品类型、单价、库存、计量单位、产地、品牌 // b.创建List集合类保存多条商品信息 // c.调用Collections.sort()方法,来对集合中的商品进行排序(先按类型升序,如果类型相同再按单价降序)java代码
时间: 2024-04-12 13:30:54 浏览: 82
Sure! Here's an example code that demonstrates the steps you mentioned:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Product {
private int productId;
private String productName;
private String productType;
private double price;
private int stock;
private String unit;
private String origin;
private String brand;
// Constructor
public Product(int productId, String productName, String productType, double price, int stock, String unit, String origin, String brand) {
this.productId = productId;
this.productName = productName;
this.productType = productType;
this.price = price;
this.stock = stock;
this.unit = unit;
this.origin = origin;
this.brand = brand;
}
// Getters and Setters
// ...
@Override
public String toString() {
return "Product{" +
"productId=" + productId +
", productName='" + productName + '\'' +
", productType='" + productType + '\'' +
", price=" + price +
", stock=" + stock +
", unit='" + unit + '\'' +
", origin='" + origin + '\'' +
", brand='" + brand + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) {
// Create a list of products
List<Product> productList = new ArrayList<>();
productList.add(new Product(1, "Product A", "Type B", 10.50, 100, "kg", "USA", "Brand X"));
productList.add(new Product(2, "Product B", "Type A", 5.99, 50, "pcs", "China", "Brand Y"));
productList.add(new Product(3, "Product C", "Type B", 15.75, 200, "kg", "Germany", "Brand Z"));
// Sort the list based on type (ascending) and price (descending)
Collections.sort(productList, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
int typeComparison = p1.getProductType().compareTo(p2.getProductType());
if (typeComparison == 0) {
return Double.compare(p2.getPrice(), p1.getPrice());
}
return typeComparison;
}
});
// Print the sorted list
for (Product product : productList) {
System.out.println(product);
}
}
}
```
In this example, we create a `Product` class with the specified attributes. We then create a `List<Product>` to store multiple product information. Finally, we use `Collections.sort()` method with a custom `Comparator` to sort the products based on type (ascending) and price (descending).
阅读全文