From 74b7b1168153edcbe860c2e283c59ba1eb95d722 Mon Sep 17 00:00:00 2001 From: Sean Gilligan Date: Tue, 9 May 2023 13:48:39 -0700 Subject: [PATCH] Transaction: use `Stream.reduce()` in `getInputSum()` --- .../java/org/bitcoinj/core/Transaction.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/core/src/main/java/org/bitcoinj/core/Transaction.java b/core/src/main/java/org/bitcoinj/core/Transaction.java index c85c58dea..b06cc52cc 100644 --- a/core/src/main/java/org/bitcoinj/core/Transaction.java +++ b/core/src/main/java/org/bitcoinj/core/Transaction.java @@ -382,20 +382,19 @@ public class Transaction extends BaseMessage { return IntMath.divide(getWeight(), 4, RoundingMode.CEILING); // round up } + /** - * Gets the sum of the inputs, regardless of who owns them. + * Gets the sum of all transaction inputs, regardless of who owns them. + *

+ * Warning: Inputs with {@code null} {@link TransactionInput#getValue()} are silently skipped. Before completing + * or signing a transaction you should verify that there are no inputs with {@code null} values. + * @return The sum of all inputs with non-null values. */ public Coin getInputSum() { - Coin inputTotal = Coin.ZERO; - - for (TransactionInput input: inputs) { - Coin inputValue = input.getValue(); - if (inputValue != null) { - inputTotal = inputTotal.add(inputValue); - } - } - - return inputTotal; + return inputs.stream() + .map(TransactionInput::getValue) + .filter(Objects::nonNull) + .reduce(Coin.ZERO, Coin::add); } /**