Caba da TI

Caba da TI

Sum BigDecimal with Stream API (Java 8)

Solution

One way to perform BigDecimal sum using Stream (Java 8) is through the Stream.reduce() method.

public class JavaSumBigDecimalStream {

   public static void main(String[] args)
   {
      List<Cow> myCows = Arrays.asList(
         new Cow("Little black", BigDecimal.valueOf(2)),
	 new Cow("Black bird", BigDecimal.valueOf(3)),
	 new Cow("Heart", BigDecimal.valueOf(1.5)));

	 BigDecimal totalMilk = myCows.stream()
	   .map(Cow::getTotalMilk) // map
	   .reduce(BigDecimal.ZERO, BigDecimal::add); // reduce

	 System.out.println(totalMilk); // 6.5
   }

}

class Cow
{
   private String name;
   private BigDecimal totalMilk;

   public Cow(String name, BigDecimal totalMilk) {
      this.name = name;
      this.totalMilk = totalMilk;
   }

   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   public BigDecimal getTotalMilk()
   {
      return totalMilk;
   }
   public void setTotalMilk(BigDecimal totalMilk)
   {
      this.totalMilk = totalMilk;
   }
}

First, the map is created, transforming the Cow objects Stream into a BigDecimal Stream. Subsequently, the reduce() method is used to sum each item in the BigDecimals Stream, that is, the following sum will be performed: 2+3+1.5, which will result in the value 6.5

References

Java 8 – How to Sum BigDecimal using Stream?

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *