import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ComparatorUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.functors.ComparatorPredicate; import java.util.ArrayList; import java.util.List; public class ProductManager { private List<Product> productList; public ProductManager() { productList = new ArrayList<>(); } public void addProduct(Product product) { productList.add(product); } public List<Product> getProducts() { return productList; } public List<Product> searchProduct(String keyword) { return new ArrayList<>(CollectionUtils.select(productList, PredicateUtils.predicateComparator( new ComparatorPredicate<>(p -> p.getName().contains(keyword)))) ); } public List<Product> sortProductsByPrice() { return ListUtils.collate(productList, ComparatorUtils.<Product>naturalComparator()); } } public class Product { private String name; private double price; private String description; private int stock; public Product(String name, double price, String description, int stock) { this.name = name; this.price = price; this.description = description; this.stock = stock; } } public class Main { public static void main(String[] args) { ProductManager productManager = new ProductManager(); productManager.addProduct(new Product("iPhone 13 Pro", 1299.99, "The latest iPhone model", 100)); productManager.addProduct(new Product("Samsung Galaxy S21", 1099.99, "Premium Android smartphone", 50)); productManager.addProduct(new Product("Sony PlayStation 5", 499.99, "Next-generation gaming console", 200)); List<Product> searchResults = productManager.searchProduct("iPhone"); for (Product product : searchResults) { System.out.println(product.getName()); } List<Product> sortedList = productManager.sortProductsByPrice(); for (Product product : sortedList) { System.out.println(product.getName() + " - " + product.getPrice()); } } }


上一篇:
下一篇:
切换中文