0
public static BigDecimal calculateSomething(List<Type> myList, Optional<Type> secondOne) {

    return myList.stream()
                 .findFirst()
                 .map(x -> x.getBalance().subtract(x.getAmount()))
                 .orElse(secondOne.map(x -> x.getBalance().subtract(x.getAmount()))
                                   .orElse(BigDecimal.ZERO));
}

I want to do some mapping on firstOne from myList if it's present. If it's not I want to do same thing on the secondOne. If it's not present either then return ZERO.

Is there a way to write this inside of one stream and reduce code duplication and stream inside of the stream on Optional?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
mladirazvijac
  • 67
  • 1
  • 10

1 Answers1

4

Yep:

return myList.stream().findFirst()
     .or(() -> secondOne)
     .map(x -> x.getBalance().subtract(x.getAmount()))
     .orElse(BigDecimal.ZERO));
sprinter
  • 27,148
  • 6
  • 47
  • 78