-2

I have a Train class, with a List<TrainCar> containing objects from a TrainCar class. I have a function in Train called getTotalWeight(). Each TrainCar has a function called getWeight() which returns a value. Can I use streams in some way to make the body of the getTotalWeight() function looking like this?

return cars.stream().//some function//;
Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

1

You could use mapToDouble to get a stream of the weights and then sum them:

return cars.stream().mapToDouble(TrainCar::getWeight).sum();
Mureinik
  • 297,002
  • 52
  • 306
  • 350