Skip to content
Advertisement

Reducing ArrayList using MyClass attributes

I have a class, MyClass, like this:

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

  public MyClass() {
    // No arguments constructor
  }

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

If I want to get the sum of amount in an ArrayList of MyClass items, usually I would do this:

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

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

// 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();

Is there a better way to do so? And how would the reduction be affected if currAmount or nextAmount is null?

Advertisement

Answer

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

Stream does not improve performance, the main idea using stream is benefit from functional programming. If you want to improve performance, please do proper benchmarking. Anyway, you can simplify the stream as below.

Long amount = myClassList.stream()
                  .mapToLong(m -> m.getAmount() == null ? 0L : m.getAmount()).sum();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement