forked from ashishps1/awesome-low-level-design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShoppingCart.java
42 lines (34 loc) · 1.05 KB
/
ShoppingCart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package onlineshopping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ShoppingCart {
private final Map<String, OrderItem> items;
public ShoppingCart() {
this.items = new HashMap<>();
}
public void addItem(Product product, int quantity) {
String productId = product.getId();
if (items.containsKey(productId)) {
OrderItem item = items.get(productId);
quantity += item.getQuantity();
}
items.put(productId, new OrderItem(product, quantity));
}
public void removeItem(String productId) {
items.remove(productId);
}
public void updateItemQuantity(String productId, int quantity) {
OrderItem item = items.get(productId);
if (item != null) {
items.put(productId, new OrderItem(item.getProduct(), quantity));
}
}
public List<OrderItem> getItems() {
return new ArrayList<>(items.values());
}
public void clear() {
items.clear();
}
}