Inspect a collection
Calculate the cart total
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class Main {
public static void main(String[] args) {
List<Item> items = List.of(
new Item("Item1", 10.0f, 2),
new Item("Item2", 5.0f, 4),
new Item("Item3", 20.0f, 1)
);
float total = getCartTotal(items);
System.out.println("Cart Total: " + total); // Output: Cart Total: 60.0
}
static float getCartTotal(List<Item> items) {
AtomicReference<Float> total = new AtomicReference<>(0.0f);
items.forEach(item -> {
total.updateAndGet(v -> v + item.getQuantity() * item.getPrice());
});
return total.get();
}
}
class Item {
private String name;
private float price;
private int quantity;
public Item(String name, float price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
}
Explanation
AtomicReference:
AtomicReference<Float> total = new AtomicReference<>(0.0f);
initializes anAtomicReference
with an initial total of 0.0f. This allows us to safely update the total within a lambda expression.Lambda Expression:
items.forEach(item -> total.updateAndGet(v -> v + item.getQuantity() * item.getPrice()));
iterates over each item in the list, and theupdateAndGet
method updates the total by adding the product ofquantity
andprice
to the current total.Returning Total:
return total.get();
returns the accumulated total value.
AtomicReference
is a thread-safe way to accumulate values in concurrent environments, though in this single-threaded context, it's just a convenient way to handle mutable state within a lambda expression.
Comments
Post a Comment