A solution using streaming
To find the minimum date, you can do something like this:
Optional<Date> minDate = list.stream().map(v -> v.logDate).min(Date::compareTo);
And to calculate the sum:
double sum = list.stream().mapToDouble(v -> v.prize).sum();
I wouldn't worry about "optimizing" this and trying to do it in one loop unless this is provably a major bottleneck in your system (unlikely). Keeping the two ideas separate makes the code easier to understand and maintain.
Your use of BigDecimal
Your code for doing balance.add(...)
to a BigDecimal
won't actually work the way you've written it because the add
method on BigDecimal
returns a new instance rather than mutating the existing instance. BigDecimal
instances are immutable. You can't assign a new value to balance
because it's effectively final
from the context of the lambda.
The idea of using BigDecimal
is a good one though. You should avoid using double
for anything where exact decimal places are important (e.g. money). If you change prize
to a BigDecimal you can't use sum()
but you can use reduce()
to fulfil the same function.
BigDecimal sum = list.stream().map(v -> v.prize).reduce(BigDecimal.ZERO, BigDecimal::add);