DEV Community

jandersonsiqueira
jandersonsiqueira

Posted on

2

Resolvendo a soma da lista de compras sem usar laços.

``import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class DesafioSemLoop {

public static BigDecimal totalCompras(List<Compra> compras) {
     return compras.stream()
            .map((c)-> c.produtos)
            .flatMap(List::stream)
            .map((item) -> BigDecimal.valueOf(item.qtd).multiply(item.valorUnitario))
            .reduce(BigDecimal.ZERO, (Acumulador, ValorAtual) -> Acumulador.add(ValorAtual) );
}`

// a partir daqui não pode mudar nada
public static void main(String... args) {
    List<Compra> compras = Arrays.asList(
            new Compra("2022-01-01",
                    Arrays.asList(
                            new ItemCompra("a", 2, new BigDecimal("12.34")),
                            new ItemCompra("b", 1, new BigDecimal("3.99")),
                            new ItemCompra("d", 3, new BigDecimal("98.14"))
                    )),
            new Compra("2022-01-02",
                    Arrays.asList(
                            new ItemCompra("a", 6, new BigDecimal("12.34")),
                            new ItemCompra("b", 1, new BigDecimal("3.99")),
                            new ItemCompra("c", 1, new BigDecimal("34.02"))
                    ))
    );

    System.out.println("O total das compras foi de " + totalCompras(compras).toPlainString());
}

public static class Compra {
    public final String data;
    public final List<ItemCompra> produtos;

    public Compra(String data, List<ItemCompra> produtos) {
        this.data = data;
        this.produtos = Collections.unmodifiableList(new ArrayList<>(produtos));
    }
}

public static class ItemCompra {
    public final String cod;
    public final int qtd;
    public final BigDecimal valorUnitario;

    public ItemCompra(String cod, int qtd, BigDecimal valorUnitario) {
        this.cod = cod;
        this.qtd = qtd;
        this.valorUnitario = valorUnitario;
    }
}
Enter fullscreen mode Exit fullscreen mode

}`

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more