49 lines
1.4 KiB
Java
49 lines
1.4 KiB
Java
package org.example;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
|
|
public class ShoppingCart {
|
|
|
|
HashMap<Product, Integer> products = new HashMap<>();
|
|
|
|
public void addProduct(Product product) {
|
|
int currentQuantity = products.getOrDefault(product, 0);
|
|
setProductQuantity(product, currentQuantity + 1);
|
|
}
|
|
|
|
public void removeProduct(Product product) {
|
|
int currentQuantity = products.getOrDefault(product, 0);
|
|
setProductQuantity(product, currentQuantity == 0 ? 0 : currentQuantity - 1);
|
|
}
|
|
|
|
public void setProductQuantity(Product product, int quantity) {
|
|
if (quantity > 0) {
|
|
products.put(product, quantity);
|
|
} else {
|
|
products.remove(product);
|
|
}
|
|
}
|
|
|
|
public int getProductQuantity(Product product) {
|
|
return products.getOrDefault(product, 0);
|
|
}
|
|
|
|
public void clearProducts() {
|
|
products.clear();
|
|
}
|
|
|
|
public Order toOrder() {
|
|
List<Product> productsInOrder = new ArrayList<>();
|
|
for (HashMap.Entry<Product, Integer> entry : products.entrySet()) {
|
|
Product product = entry.getKey();
|
|
int quantity = entry.getValue();
|
|
for (int i = 0; i < quantity; i++) {
|
|
productsInOrder.add(product);
|
|
}
|
|
}
|
|
return new Order(productsInOrder);
|
|
}
|
|
}
|