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")
?
If you can use lambdaj, you can write something like:
For some more examples of how to use lambdaj, see the Features page on the lambdaj wiki.