Home > Back-end >  How to get sum of List element by group
How to get sum of List element by group

Time:07-06

I have list of Cars <CarsName, Price>. I need to make some logic in method named sumOfPrice, but I have no idea how to do that. Please help or give some sugestion.

//file Car.class
class Car {
    private String name;
    private double price;
    public Car (String name, double price){
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public double getPrice(){
        return price;
    }
}


//file Main.class
public class MainClass {
    public static void main(String[] args) {
        Map<String, Double> sumList = new HashMap<>();
        Map<String, Double> carList = new HashMap<>();
        carList.put("BMW X5", 35000.00);
        carList.put("BMW X5", 33000.00);
        carList.put("BMW X3", 30000.00);
        carList.put("BMW X3", 29000.00);

        sumList = sumOfPrice(carList);

//print my list  
        for (String i : sumList.keySet()) {
            System.out.println(i   " "   sumList.get(i));
        }
    }
    public Map<String, Double> sumOfPrice(List<Car> cars) {
        Map<String, Double> sum = new HashMap<String, Double>();
        for (Car car : cars) {
            //logic TODO:
        }
        return sum;
    }
}

How to get sum of prices by car? Output must be group by car name (model).

Output must be like:

BMW X5 68000

BMW X3 59000

CodePudding user response:

public Map<String, Double> sumOfPrice(List<Car> cars) {
    Map<String, Double> sum = new HashMap<String, Double>();
    for (Car car : cars) {
        if(sum.containKey(car.getName()) { // Checkes if car already exists in sum.
            sum.put(car.getName(), sum.get(car.getName())   car.getPrice()); // Adds current car price, to already car sum price.
        } else sum.put(car.getName(), car.getPrice());
    }
    return sum;
}
  •  Tags:  
  • java
  • Related