我正在学习 Java 8 Lambda 表达式。我对 Lambda 有了基本的了解。但我不明白以下代码如何适用于代码片段:-
return new Quote(quote,
stock.getQuote().getPrice()); // Confusion here.
这是返回到以下函数.collect(Collectors.toList())
还是完全从Lambda返回。请详细解释一下它是如何工作的?
public List<Quote> getStock(){
List<String> quotes = new ArrayList<>();
return quotes
.stream()
.map(quote -> {
Stock stock = getStockPrice(quote);
return new Quote(quote, stock.getQuote().getPrice()); // Confusion here
})
.collect(Collectors.toList());
}
最佳答案
它从 lambda 返回。请记住,lambda 基本上只不过是一个匿名函数。
您可以在没有 Streams 的情况下重写代码,如下所示:
public List<Quote> getStock() {
List<String> quotes = new ArrayList<>();
List<Quote> returnList = new ArrayList<>();
for (String quote : quotes)
{
Quote theQuote = myLambda(quote);
returnList.add(theQuote);
}
return returnList;
}
private Quote myLambda(String quote)
{
Stock stock = getStockPrice(quote);
return new Quote(quote, stock.getQuote().getPrice());
}
return
在您的版本中使用 lambda 和 return
在我的版本中,其行为方式完全相同。它们从函数返回以允许处理下一个报价。
还值得注意的是,您的 getStock
方法创建一个新的空 ArrayList 并从该列表创建一个流。因此,结果 List<Quote>
当前将始终为空。
关于lambda - 这个 lambda 表达式有什么作用以及如何作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45955996/