所以我有变量Optional<Collection<Student>>,我想使用.findFirst()lambda方法查找Student地址。
我现在做的方式是这样
Optional<Collection<Student>> students = ...;
return students.map(s -> s.stream()
.filter(...)
.findFirst())
.orElse(Optional.empty());
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法可以做到这一点,这样我就不会在地图内部创建流了?
BigDecimal getInterest(List<Investment> investments) {
BigDecimal interest = BigDecimal.ZERO;
for (Investment i: investments) {
i.getTransactions().stream()
.map(Transaction::getAmount)
.forEach(interest::add);
}
return interest;
}
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是它总是返回零.看起来好像 .forEach()没有消耗它的论点.但是如果我按照下面的方式编写它,一切都运行正常.任何人都知道为什么第一种方法不起作用?
BigDecimal getInterest(List<Investment> investments) {
BigDecimal interest = BigDecimal.ZERO;
for (Investment i: investments) {
interestPaid = interest.add(i.getTransactions().stream()
.map(Transaction::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add));
}
return interest;
}
Run Code Online (Sandbox Code Playgroud)