6

I have a simple class:

class Simple {
    private String count;
    private BigDecimal amount;
    private String label;
}

and have a List: List<Simple> simples = new ArrayList<>(); how I can sum all amounts of all simples in list with Lambda in Java 8?

Jack Daniel
  • 2,397
  • 8
  • 33
  • 58

2 Answers2

28

It is quite easy with a Stream and a reducer :

BigDecimal sum = simples
    .stream()
    .map(Simple::getAmount)
    .reduce(BigDecimal::add)
    .get();
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • 11
    You may use `.orElse(BigDecimal.ZERO)` instead of `.get()` to get a useful result for empty lists. Or use `.reduce(BigDecimal.ZERO, BigDecimal::add)` in the first place, so you don’t have to deal with an `Optional` at all… – Holger Jun 30 '16 at 13:55
  • 2
    My code giving error at BigDecimal::add saying "cannot resolve method add" Any help ? – Nitish Kumar Sep 09 '17 at 16:42
  • 4
    You will notice this error on reduce when the mapped value is not of type BigDecimal, if the mapped value was of type double you can do .map(p -> BigDecimal.valueOf(p)) – Siva Apr 29 '19 at 13:21
  • this code is not working when getAmount() method return null – charu joshi Sep 14 '19 at 10:30
  • @Arnaud Denoyelle, so let me see if I understood, from the stream you apply a map function to get the amount, from amount you made a reduce to group the values using add()? And what is the use for the get() in the final ? I didn't understand for what is the get – lipesmile Jul 03 '20 at 19:53
  • @lipesmile Without it, you get an `Optional`. The `get` just converts it to a `BigDecimal` – Arnaud Denoyelle Jul 03 '20 at 20:38
  • @ArnaudDenoyelle Thanks for the explanation – lipesmile Jul 16 '20 at 21:29
  • flawless answer arnaud! – Gaurav Dec 21 '20 at 12:21
  • In order to prevent null values, you might want to add Object::nonNull function as a predicate. `.filter(Objects::nonNull)` – RIP SunMicrosystem Mar 08 '21 at 02:46
6

Try:

BigInteger sum = simples.stream()
                        .map(Simple::getAmount)
                        .reduce(BigInteger.ZERO, BigInteger::add);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • once getAmount is null : Exception in thread "main" java.lang.NullPointerException at java.math.BigDecimal.add(BigDecimal.java:1291) – Tiago Medici Jun 16 '20 at 12:20