Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best calculate the sum of a objects' property?

Tags:

java

If an object car has a property fuel, and I have a list of these objects cars: how can I best calculate the sum of this property getCarsFuel() of all objects in the list?

class CarStock {
    List<Car> cars;

    public int getCarsFuel() {
        int result = 0;     

        for (Car car : cars) {
            result += car.getFuel();
        }

        return result;
    }
}

class Car {
    int fuel;
}

Are there better ways, or can't it be done less "boilerplate". I could image something like sum(List<T> list, String property) -> sum(cars, "fuel") ?

like image 534
membersound Avatar asked Nov 21 '12 22:11

membersound


1 Answers

If you can use lambdaj, you can write something like:

import static ch.lambdaj.Lambda.*;

List<Car> cars = ...;
int result = sumFrom(cars).getFuel();

For some more examples of how to use lambdaj, see the Features page on the lambdaj wiki.

like image 107
Martin Ellis Avatar answered Nov 09 '22 08:11

Martin Ellis