I have a dart list:

List<Car> cars = new List<Car>();

//Car(brand, quantity)

Car car = new Car ("nissan", 2);
cars.add(car);

car = new Car("nissan", 4);
cars.add(car);

car = new Car("toyota", 3);
cars.add(car);

car = new Car("nissan", 5);
cars.add(car);

car = new Car("toyota", 2);
cars.add(car);

How can i get a list of Cars which should only contains 2 records (which is the sum of the quantity):

Car("nissan", 11)
Car("toyota", 5)


Solution 1: Manish

You can use a map literal and then count using a forEach loop.

  var carMap = {};
  cars.forEach((car) {
    String key = car.brand;
    if (carMap.containsKey(key)) {
      carMap[key] += car.quantity;
    } else {
      carMap[key] = car.quantity;
    }
  });
  print(carMap);