Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Lambda Expression works

Tags:

in an interview , interviewer ask me following query

int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Func<int, int> func = i =>
{
    Console.Write(array[i]);
    return i;
};

var result = array.Where(e => e <= func(2)).ToArray();

so will any one guide me how e <= func(2) thing works? and how last line i.e

var result = array.Where(e => e <= func(2)).ToArray();

works?

like image 632
Usman Avatar asked Jan 15 '12 14:01

Usman


People also ask

How do lambda expressions work internally?

Every lambda expression in Java is internally mapped to a functional interface. The functional interface to which a lambda expression will be mapped is determined by the compiler from its surrounding context at compile time. // A lambda expression that accepts no arguments and returns void () -> System.

What is a lambda expression example?

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.

Why do we use lambda expression?

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .

How do you call a lambda function in Java?

You can invoke a Lambda function by creating an AWSLambda object and invoking its invoke method. Create an InvokeRequest object to specify additional information such as the function name and the payload to pass to the Lambda function.


1 Answers

It may be easier to understand if you use parentheses:

var result = array.Where(e => (e <= func(2))).ToArray();

This

e => ...

Constructs a function which takes one argument.

This

e <= func(2)

compares e to func(2). func(2) calls the function func with the argument 2.

All in all, the <= has nothing to do with =>. They are two completely different operators. To summarize ... => ... constructs a function. ... <= ... compares the arguments.

like image 131
Lasse Espeholt Avatar answered Sep 23 '22 22:09

Lasse Espeholt