This question is a follow-up to an earlier question: Adding up BigDecimals using Streams
The question related to adding up BigDecimal
s using Java 8 Stream
s and Lambda expressions. After implementing the answers given, I ran into another problem: whenever the stream is empty, the Optional::get()
method throws a NoSuchElementException
.
Consider the following code:
public static void main(String[] args){
LinkedList<BigDecimal> values = new LinkedList<>();
// values.add(BigDecimal.valueOf(.1));
// values.add(BigDecimal.valueOf(1.1));
// values.add(BigDecimal.valueOf(2.1));
// values.add(BigDecimal.valueOf(.1));
// Classical Java approach
BigDecimal sum = BigDecimal.ZERO;
for(BigDecimal value : values) {
System.out.println(value);
sum = sum.add(value);
}
System.out.println("Sum = " + sum);
// Java 8 approach
values.forEach((value) -> System.out.println(value));
System.out.println("Sum = " + values.stream().reduce((x, y) -> x.add(y)).get());
}
The vanilla Java code has no problem with an empty collection, but the new Java 8 code does.
What is the most elegant way to avoid a NSEE here? Certainly we could do:
System.out.println("Sum = " + values == null || values.isEmpty() ? 0 : values.stream().reduce((x, y) -> x.add(y)).get());
But is there a Java-8-ish way to handle empty collections?