A company processes financial transactions. Each transaction is represented by a Transaction object with fields: amount (double), currency (String), and type (String). The requirement is to compute the total amount of all transactions of type 'SALE' in USD. The transactions are stored in a List<Transaction>. Which code correctly accomplishes this using streams?
Trap 1: transactions.stream().mapToDouble(Transaction::amount).filter(t ->…
mapToDouble returns DoubleStream, which does not have type method; filter cannot be applied after mapToDouble in this way.
Trap 2: transactions.stream().filter(t -> t.type().equals("SALE")).filter(t…
Filters by type then currency, but currency filter is not needed if only SALE transactions are considered; also missing currency check for USD.
Trap 3: transactions.stream().map(Transaction::amount).reduce(0.0, (a, b)…
Missing filter for type and currency; also reduce works but sum() is more concise.
- A
transactions.stream().mapToDouble(Transaction::amount).filter(t -> t.type().equals("SALE")).sum()
Why wrong: mapToDouble returns DoubleStream, which does not have type method; filter cannot be applied after mapToDouble in this way.
- B
transactions.stream().filter(t -> t.type().equals("SALE")).filter(t -> t.currency().equals("USD")).mapToDouble(Transaction::amount).sum()
Why wrong: Filters by type then currency, but currency filter is not needed if only SALE transactions are considered; also missing currency check for USD.
- C
transactions.stream().map(Transaction::amount).reduce(0.0, (a, b) -> a + b)
Why wrong: Missing filter for type and currency; also reduce works but sum() is more concise.
- D
transactions.stream().filter(t -> t.type().equals("SALE") && t.currency().equals("USD")).mapToDouble(Transaction::amount).sum()
Correctly filters by type and currency, then sums amounts.