Search code examples
javajava-17

How to get the sum of prodcuts from a specific country


I am looking to get sum of all products from belgium . Aparently i get sum of all products from the lsit . I use this sum = productsList.stream().mapToInt(Products::getPrice).sum(); to get out my sum of products belgium but i see that with this code is taking out sum of all produts
Can somoane explain to me what i am doing wrong in my code ? i have a class Prodcts and This is my Main:

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class sumProdBelgium {
    public static void main(String[] args) {
        Products product1 = new Products("ham", LocalDate.of(2020, 10, 15), "belgium", 3);
        Products product2 = new Products("bacon", LocalDate.of(2021, 1, 17), "RPA", 4);
        Products product3 = new Products("bread", LocalDate.of(2022, 2, 2), "Poland", 1);
        Products product4 = new Products("cheese", LocalDate.of(2023, 1, 19), "RPA", 5);
        Products product5 = new Products("tomato", LocalDate.of(2019, 12, 2), "belgium", 1);

        List<Products> productsList = new ArrayList<>(List.of(product1, product2, product3, product4, product5));


        int sumBelgiumIteration = getSumbelgiumIteration(productsList);
        System.out.println("Sum product belgium iteration is : " + sumBelgiumIteration + " euro");
    }


    public static int getSumbelgiumIteration(List<Products> productsList) {
        int sum = 0;
        //iterate trough list 
        for (Iterator<Products> iterator = productsList.iterator(); iterator.hasNext(); ) {
            //if contain "belgium"
            if (iterator.next().getCountry().equalsIgnoreCase("belgium")) {
//  sum  is = to  belgium product (is not this the way  of taking the products from "belgium")
                sum = productsList.stream().mapToInt(Products::getPrice).sum();
            }
        }
        return sum;
    }
}

Expected output = 4

Output that i get is 14 (total sum of all products)


Solution

  • sum = productsList.stream().mapToInt(Products::getPrice).sum();
    

    This takes all the products, iterates through them and maps them to an integer, and sums that up. It's clear that you want to filter and get all the "Belgium" elements.

    This is easily achieved through .filter().

    int sumOfBelgiumElements = productsList.stream()
            .filter(product-> product.getCountry().equalsIgnoreCase("belgium")) // Get only the elements that have Belgium as country
            .mapToInt(Products::getPrice) // Map
            .sum(); // sum
    

    This sums up what you are trying to do in your method. So you can replace your code with this.

    Another thing to be noted is that you are overwriting the value of sum with every iteration. That will not lead to what you need.