I want to use Java's stream API to do some calculations on a list of objects:
List<Item>.stream()...
The Item
class contains many attributes. For some of those I need to take the average value across all items in the collection, for other attributes I need to do other forms of calculations. I have been doing separate stream/collector calls to achieve this and although I'm not running into any performance issues (because the list size is usually about 100) I want to learn how to be more concise, aka loop once.
ItemCalculation itemCalculation = ItemCalculation.builder()
.amountOfItems(itemList.size())
.averagePrice(itemList.stream()
.mapToDouble(item -> item.getPrice())
.average()
.getAsDouble())
.averageInvestmentValue(itemList.stream()
.mapToDouble(item -> getTotalInvestmentValue(item.getInvestmentValue(), item.getInvestmentValuePackaging()))
.average()
.getAsDouble())
.highestWarrantyLimit(itemList.stream()... etc.
I read about creating a custom collector, but it seems a bit weird to have my "calculation" class be just one line (stream->customCollector) and then have a very bloated collector class that does the actual logic. Especially because different attributes are collected in a different way I would need many different intermediate count and other variables. Any thoughts?