使用 MyClass 属性减少 ArrayList<MyClass>

Reducing ArrayList<MyClass> using MyClass attributes

我有一个class,MyClass,像这样:

public class MyClass() {
  String name;
  Long amount;

  public MyClass() {
    // No arguments constructor
  }

  public Long getAmount() {
    return this.amount;
  }
}

如果我想在 MyClass 项目的 ArrayList 中获得 amount 的总和,通常我会这样做:

// assuming ArrayList<MyClass> myClassList
Long amount = 0L;
for (MyClass x : myClassList) {
  amount += x.getAmount();
}

但现在为了提高性能,我正在尝试使用Stream.reduce()。我的做法:

// assuming ArrayList<MyClass> myClassList
// reduce all MyClass items to a single MyClass item that holds the total amount
Long amount = myClassList.stream().reduce(new MyClass(), 
(curr, next) -> {
  Long currAmount = curr.getAmount() != null ? curr.getAmount() : 0L;  // subtotal
  Long nextAmount = next.getAmount() != null ? next.getAmount() : 0L;  // next value to add
  curr.setAmount(currAmount + nextAmount);  // next subtotal
  return curr;
}).getAmount();

有更好的方法吗?如果 currAmountnextAmount 为空,减少会受到怎样的影响?

But now to improve performance, I am trying to use Stream.reduce()

Stream does not improve performance, the main idea using stream is . If you want to improve performance, please do proper benchmarking。 不管怎样,你可以简化流如下。

Long amount = myClassList.stream()
                  .mapToLong(m -> m.getAmount() == null ? 0L : m.getAmount()).sum();

您也可以像下面这样使用 reduce:

Long amount = myClassList.stream()
            .filter(m -> m.getAmount() != null)
            .mapToLong(Product::getAmount)
            .reduce(0, Long::sum);