-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathShoppingCart.java
More file actions
53 lines (37 loc) · 1.24 KB
/
ShoppingCart.java
File metadata and controls
53 lines (37 loc) · 1.24 KB
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
43
44
45
46
47
48
49
50
51
52
53
package com.example.shop;
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
private List<Item> items = new ArrayList<>();
private Discount discount;
public void addItem(Item newItem){
if ( newItem.getQuantity() > 0) {
for (Item existingItem : items) {
if (existingItem.getId().equals(newItem.getId())) {
int updatedQuantity = existingItem.getQuantity() + newItem.getQuantity();
existingItem.setQuantity(updatedQuantity);
return;
}
}
this.items.add(newItem);
}
}
public List<Item> getItems() {
return items;
}
public void removeItem(Item item){
this.items.remove(item);
}
public void setDiscount(Discount discount) {
this.discount = discount;
}
public double getTotalPrice(){
double totalPrice = items.stream()
.mapToDouble(item -> item.getPrice() * item.getQuantity())
.sum();
if (discount != null && discount.getPercentage() <= 100 && discount.getPercentage() > 0) {
return discount.applyDiscount(totalPrice);
}
return totalPrice;
}
}