package utils; import models.Order; import models.Product; import java.util.HashMap; public class TaskUtils { public static LinkedList FindMostPopularProducts(Iterable orders) { HashMap productSales = new HashMap(); for (Order order : orders) { if (!productSales.containsKey(order.productID)) { productSales.put(order.productID, order.productAmount); } else { productSales.replace(order.productID, productSales.get(order.productID) + order.productAmount); } } LinkedList mostPopularProducts = new LinkedList(); int mostPopularCount = 0; for (String product : productSales.keySet()) { int count = productSales.get(product); if (count > mostPopularCount) { mostPopularCount = count; mostPopularProducts = new LinkedList(); mostPopularProducts.add(product); } else if (count == mostPopularCount) { mostPopularProducts.add(product); } } return mostPopularProducts; } public static int CountProductSales(Iterable orders, String product) { int sales = 0; for (Order order : orders) { if (order.productID.equals(product)) { sales += order.productAmount; } } return sales; } public static Product FindByID(Iterable products, String id) { for (Product product : products) { if (product.ID.equals(id)) { return product; } } return null; } public static LinkedList FindByID(Iterable products, Iterable ids) { LinkedList foundProducts = new LinkedList(); for (String id : ids) { foundProducts.add(FindByID(products, id)); } return foundProducts; } public static LinkedList FilterByQuantitySoldAndPrice(Iterable products, Iterable orders, int minSold, float maxPrice) { LinkedList filtered = new LinkedList(); for (Product product : products) { if (product.price < maxPrice) { int sold = CountProductSales(orders, product.ID); if (sold >= minSold) { filtered.add(product); } } } return filtered; } public static LinkedList MergeOrders(Iterable orders) { HashMap ordersByName = new HashMap<>(); for (Order order : orders) { var key = order.customerSurname + order.customerName + order.productID; if (ordersByName.containsKey(key)) { ordersByName.get(key).productAmount += order.productAmount; } else { ordersByName.put(key, new Order(order.customerSurname, order.customerName, order.productID, order.productAmount)); } } LinkedList mergedOrders = new LinkedList(); for (Order order : ordersByName.values()) { mergedOrders.add(order); } return mergedOrders; } public static LinkedList FindCustomerWithSingleProduct(Iterable orders) { HashMap> ordersByCustomer = new HashMap<>(); for (Order order : MergeOrders(orders)) { var key = order.customerName + order.customerSurname; if (!ordersByCustomer.containsKey(key)) { ordersByCustomer.put(key, new LinkedList<>()); } ordersByCustomer.get(key).add(order); } LinkedList finalList = new LinkedList(); for (LinkedList customerOrders : ordersByCustomer.values()) { if (customerOrders.get(1) == null) { finalList.add(customerOrders.get(0)); } } return finalList; } }