packagecom.harishgowda84.java8;importjava.math.BigDecimal;importjava.util.Arrays;importjava.util.List;publicclassBigDecimalDemo{publicstaticvoidmain(String[]args){List<BigDecimal>numbers=Arrays.asList(newBigDecimal(8.9),newBigDecimal(14.5),newBigDecimal(123.67),newBigDecimal(25.6),newBigDecimal(4.3));BigDecimalsum=BigDecimal.ZERO;for(BigDecimalelement:numbers){sum=sum.add(element);}System.out.println("Sum of all values is: "+sum);}}
packagecom.harishgowda84.java8;importjava.math.BigDecimal;importjava.util.Arrays;importjava.util.List;publicclassBigDecimalDemo{publicstaticvoidmain(String[]args){List<BigDecimal>numbers=Arrays.asList(newBigDecimal(8.9),newBigDecimal(14.5),newBigDecimal(123.67),newBigDecimal(25.6),newBigDecimal(4.3));BigDecimalsum=numbers.stream().reduce(BigDecimal.ZERO,BigDecimal::add);System.out.println("Sum of all values is: "+sum);}}
We have used reduce() method with an initial value of BigDecimal.ZERO and a binary operator of BigDecimal::add to sum the BigDecimal numbers in the stream. Finally, we printed the sum to the console.