如果当前不存在,则在流中放置另一个 Optional
Underlay another Optional in stream if current is not present
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));
}
如果存在,我想对 myList 中的 firstOne 进行一些映射。如果不是,我想在 secondOne 上做同样的事情。如果它也不存在,那么 return 零。
有没有一种方法可以将其写入一个流中并减少代码重复并减少 Optional 流中的流?
是的:
return myList.stream().findFirst()
.or(() -> secondOne)
.map(x -> x.getBalance().subtract(x.getAmount()))
.orElse(BigDecimal.ZERO));
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));
}
如果存在,我想对 myList 中的 firstOne 进行一些映射。如果不是,我想在 secondOne 上做同样的事情。如果它也不存在,那么 return 零。
有没有一种方法可以将其写入一个流中并减少代码重复并减少 Optional 流中的流?
是的:
return myList.stream().findFirst()
.or(() -> secondOne)
.map(x -> x.getBalance().subtract(x.getAmount()))
.orElse(BigDecimal.ZERO));