masiboo
masiboo

Reputation: 4719

What does this lambda expression do and how

I'm learning Java 8 Lambda expressions. I got the basic understanding of Lambda. But I don't understand how following code is working for the code snippet:-

return new Quote(quote, 
                     stock.getQuote().getPrice());  // Confusion here.

Does this return to the following function which is .collect(Collectors.toList()) or return from the Lambda completely. Please explain in details how does it work?

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

Upvotes: 2

Views: 123

Answers (2)

Michael
Michael

Reputation: 44240

It returns from the lambda. Remember, a lambda is basically nothing more than an anonymous function.

You could rewrite your code, without Streams, as:

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

The return in your version using a lambda and the return in my version act in exactly the same way. They return from the function to allow the next quote to be processed.

It's also worth noting that your getStock method creates a new empty ArrayList and creates a stream from that list. As such, the resulting List<Quote> will always currently be empty.

Upvotes: 2

Eugene
Eugene

Reputation: 120998

This:

.map(quote -> {
       Stock stock = getStockPrice(quote);
       return new Quote(quote,  stock.getQuote().getPrice());
    })

takes a String as input and returns a Quote; it's a Function<String, Quote>. You can implement this Function via a class :

class FromStringToQuote implements Function<String, Quote> {

      public Quote apply (String quote) ...

May be that will make it more clear.

For each element from quotes (which are Strings) you map these to a Quote via the lambda expression.

After one is mapped, it is sent to the Collectors.toList(); that collects that to a List.

Upvotes: 2

Related Questions