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

  1. AtomicReference: AtomicReference<Float> total = new AtomicReference<>(0.0f); initializes an AtomicReference with an initial total of 0.0f. This allows us to safely update the total within a lambda expression.

  2. Lambda Expression: items.forEach(item -> total.updateAndGet(v -> v + item.getQuantity() * item.getPrice())); iterates over each item in the list, and the updateAndGet method updates the total by adding the product of quantity and price to the current total.

  3. Returning Total: return total.get(); returns the accumulated total value.

Using 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

Popular posts from this blog

Transform values with a stream

Collections Framework