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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With